Sealed and data
- Kotlin course
- Intermediate
- Lesson 26/116
- 5 min
Learn to use data classes inside sealed classes.
data class subtype
A subtype of a sealed class can be a data class. This is convenient for states that carry fields; each subtype has its own data.
Example: sealed class Message; data class Text(val content: String) : Message(); data class Image(val url: String) : Message(). Text carries a content string, Image carries a URL. A Message instance can be Text("hi") or Image("a.png"). When when identifies the type, Kotlin performs a smart cast and you can access the subtype's fields directly.
Field access with smart cast
When you check the type with when on a sealed class, Kotlin automatically applies a smart cast. You can access the subtype's fields directly; no explicit cast is needed.
Example: when (m) { is Text -> m.content; is Image -> m.url }. In the is Text branch, m is automatically cast to Text; m.content is directly accessible. Similarly m.url works in the is Image branch. This makes sealed class with when concise and safe.
Practice The Message sealed class and data class subtypes
Define a sealed class named Message. Add two data class subtypes: Text(val content: String) and Image(val url: String), both inheriting from Message(). Write a function describe(m: Message): String whose body uses when (m) to return m.content for Text and m.url for Image. In main create a Text("hi") instance and print the result of describe.
Starter code
// Define the Message sealed class
// data class Text and Image subtypes
// describe function: branch with when
// instantiate Text in main, print describeSample solution
sealed class Message
data class Text(val content: String) : Message()
data class Image(val url: String) : Message()
fun describe(m: Message): String {
return when (m) {
is Text -> m.content
is Image -> m.url
}
}
fun main() {
val m: Message = Text("hi")
println(describe(m))
}Expected output
hi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of the following can be a data class subtype of a sealed class?
- class Plain : Message()
- object Loading : Message()
- data class Text(val content: String) : Message() Correct answer
- interface Drawable : Message()
Explanation: A data class inherits a sealed class as a subtype that carries fields.
2 Complete the data class subtype definition
data class Text(val content: String) : ____()
data class Image(val url: String) : Message()
data class Text(val content: String) : Message()
data class Image(val url: String) : Message()
Explanation: data class Text inherits from the Message sealed class.
3 Match the sealed + data pattern
| Term | Meaning |
|---|---|
sealed class Message |
Closed base class |
data class Text |
Field-carrying subtype |
is Text -> m.content |
Smart cast access |
when (m) |
Branching |