Kotlin·Kotlin from syntax to a coroutine app

Classes and data classes

Model data with data classes, sealed types and properties.

Beginner 13 min read Lesson 5 of 300 Challenge included
What you will be able to do
  • Use data class for value-like data.
  • Use sealed class for a closed set of states.
  • Use copy for immutable updates.
  • Use when exhaustively over sealed types.

In plain English

A data class generates equals, hashCode, toString and copy. Sealed classes model a closed set of states, which pairs perfectly with exhaustive when expressions.

Models.ktKotlin
data class User(val id: String, val name: String)

sealed class Result {
    data class Ok(val value: String) : Result()
    data class Error(val message: String) : Result()
}

fun render(result: Result) = when (result) {
    is Result.Ok -> result.value
    is Result.Error -> result.message
}
Your turn

Copy a data class

Easy

Create a copy of a user with the name changed to Ada.

KOTLIN · starter
user.copy()
Check your understanding before moving on.
Knowledge checkQuestion 1

Which class type is ideal for a closed set of states?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Coroutines
Lesson 5 of 300 · 0% of course