Classes and data classes
Model data with data classes, sealed types and properties.
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.
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
EasyCopy a data class
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 inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.