How Do I Use Kotlin to Model Tasks in an Android App?

In article 1, you created Task Notes and its empty screen. Now you will describe the data behind a task using Kotlin. You will create a Task model, prepare sample tasks, and display one task on the existing screen. The next article will turn those samples into a scrolling list.

Practical goal

By the end, you will be able to declare typed properties, use default and named arguments, create a read-only list, and produce an updated task with copy().

Continue with the same Android Studio project. This example keeps the package org.kodejava.tasknotes, the generated TaskNotesTheme, and minimum SDK API 24 from article 1. If you used your own package, adjust the package declarations and imports below.

1. Create the Task model

Create the model package below org.kodejava.tasknotes. Add this file:

File: app/src/main/java/org/kodejava/tasknotes/model/Task.kt

package org.kodejava.tasknotes.model

data class Task(
    val id: Long,
    val title: String,
    val isCompleted: Boolean = false
)

A model describes information that the app works with. Here, each task has three properties:

Property Type Purpose
id Long Identifies the task even when its title changes
title String Holds the text shown to the user
isCompleted Boolean Records whether the task is done

The colon introduces a type. Boolean has two values: true and false. The default value means a new task starts incomplete unless you supply another value.

String does not accept null. It still accepts empty text such as ""; non-null types do not replace input validation. You will add form validation in a later article.

The data keyword asks Kotlin to generate useful operations such as equality checks, readable text output, and copying. Keep the properties in the primary constructor so those generated operations include them. See the official data class documentation.

2. Understand val and named arguments

This is an example of constructing a task; you do not need to add it to a file yet:

val task = Task(id = 1L, title = "Learn Kotlin basics")

val declares a reference that cannot be reassigned. The model also uses val properties, so you cannot assign a new title directly to an existing task.

1L is a Long literal. Named arguments such as title = ... make constructor calls easier to read. Since we omitted isCompleted, its value is false.

Kotlin also has var for variables that can be reassigned. We use val here to make changes explicit through new objects.

3. Prepare reusable sample data

Create a data package and add the following file:

File: app/src/main/java/org/kodejava/tasknotes/data/SampleTasks.kt

package org.kodejava.tasknotes.data

import org.kodejava.tasknotes.model.Task

fun sampleTasks(): List<Task> = listOf(
    Task(id = 1L, title = "Learn Kotlin basics"),
    Task(id = 2L, title = "Create the Task model", isCompleted = true),
    Task(id = 3L, title = "Build the task list")
)

fun declares a function. This function takes no arguments and returns a List<Task>, meaning a list whose elements are tasks. The = introduces a function with a single expression as its body.

listOf() creates the sample list. List exposes read-only operations: callers can inspect its elements but cannot call add() through that interface. A read-only interface is not a general guarantee that an underlying collection can never change. Our sample contains tasks with read-only properties and exposes no mutation operations.

The sample IDs are distinct and remain the same each time this function is called. They are manually assigned tutorial values; the function does not generate IDs for future user-created tasks. A title is not an ID because two tasks may have the same title.

Reference: Kotlin collections overview.

4. Display a task on the existing screen

In MainActivity.kt, add this import alongside the existing imports:

import org.kodejava.tasknotes.data.sampleTasks

Replace only the existing TaskNotesScreen() function with the code below. Keep MainActivity, its Scaffold and innerPadding, all existing Compose imports, and TaskNotesScreenPreview() from article 1.

File: app/src/main/java/org/kodejava/tasknotes/MainActivity.kt

@Composable
private fun TaskNotesScreen(modifier: Modifier = Modifier) {
    val tasks = sampleTasks()
    val task = tasks.first()
    val status = if (task.isCompleted) "Completed" else "Not completed"

    Column(
        modifier = modifier.fillMaxSize().padding(24.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Text(
            text = "Task Notes",
            style = MaterialTheme.typography.headlineMedium
        )
        Text(
            text = task.title,
            style = MaterialTheme.typography.bodyLarge
        )
        Text(text = "Status: $status")
        Text(text = "Sample tasks: ${tasks.size}")
    }
}

Kotlin infers the types of tasks, task, and status from their values. first() reads the first element. It is safe here because our sample function always returns three tasks; it would throw an exception for an empty list.

An if expression produces the status text. String templates insert values into text: $status inserts a variable, while ${tasks.size} evaluates an expression.

This screen only reads fixed sample data. Calling sampleTasks() during composition is acceptable for this tiny example; it is not a strategy for loading database data. Interactive state and its ownership come later in the series.

5. Create an updated task with copy()

To try a completed version, replace this line inside TaskNotesScreen():

val task = tasks.first()

with:

val original = tasks.first()
val task = original.copy(isCompleted = true)

The copied task keeps the original ID and title but has a new completion value. The original task and the task stored in the sample list remain incomplete. Copying an object does not replace an element in a list.

copy() is shallow: nested objects would still be shared. This model contains only a number, text, and a Boolean, so no mutable nested collection is involved.

After checking the result, restore val task = tasks.first() so your project matches the starting point for article 3.

6. Verify the result

  1. Sync the project if Android Studio requests it, then run the app on the emulator or phone used in article 1.
  2. Check that the screen shows the following text:
Task Notes
Learn Kotlin basics
Status: Not completed
Sample tasks: 3
  1. Refresh the existing Compose preview. It should show the same sample content.
  2. Try the copy() change from step 5. The status should become Completed, with the same title and sample count.
  3. Restore the original line and run again.

If Task or sampleTasks is unresolved, check the file package declarations and imports. If the compiler reports a type mismatch for an ID, use a Long literal such as 1L. If the preview cannot load, resolve build errors before refreshing it.

These are verification steps for your project. This draft’s Android build and device behavior have not been executed in an Android SDK environment.

Practice

  • Add a fourth sample task with ID 4L. Verify that the count becomes 4.
  • Display tasks[1] instead of the first task. The second task should show Completed. List indexes start at zero.
  • Use copy(title = "Review Kotlin basics") on the first task and observe that the original sample title stays unchanged.

Restore the three original samples and tasks.first() before continuing to the next article.

Gradle dependencies and compatibility

No additional Gradle dependencies are required. The model and sample function use the Kotlin standard library supplied by the existing Kotlin Android project. The screen reuses the Compose dependencies configured in article 1.

Keep the existing plugin and dependency versions in build.gradle.kts, app/build.gradle.kts, and gradle/libs.versions.toml if present. This lesson introduces no version-specific library API and does not require a Kotlin, Android Gradle Plugin, or Compose upgrade. Official Compose setup guidance remains the reference for project configuration.

Next in the series

In article 3, How Do I Display Tasks in a LazyColumn with Jetpack Compose?, you will reuse Task and sampleTasks() to render the task list.

Leave a Comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.