Data Classes and Sealed Types
Sealed When
Use when to handle each sealed subclass.
sealed-when
`when` pairs naturally with sealed classes because every subclass can be listed.
Sealed When
SealedWhen.kt
Replay: real traced execution (multi-file project)
sealed class Level
class LowLevel : Level()
class HighLevel : Level()
fun describe(level: Level): String {
return when (level) {
is LowLevel -> "low"
is HighLevel -> "high"
}
}
fun main() {
val score = 8
val level: Level
if (score >= 8) {
level = HighLevel()
} else {
level = LowLevel()
}
val label = describe(level)
println("score=$score")
println("label=$label")
}
sealed class Level
class LowLevel : Level()
class HighLevel : Level()
fun describe(level: Level): String {
return when (level) {
is LowLevel -> "low"
is HighLevel -> "high"
}
}
fun main() {
val score = 3
val level: Level
if (score >= 8) {
level = HighLevel()
} else {
level = LowLevel()
}
val label = describe(level)
println("score=$score")
println("label=$label")
}
sealed class Level
class LowLevel : Level()
class HighLevel : Level()
fun describe(level: Level): String {
return when (level) {
is LowLevel -> "low"
is HighLevel -> "high"
}
}
fun main() {
val score = 10
val level: Level
if (score >= 8) {
level = HighLevel()
} else {
level = LowLevel()
}
val label = describe(level)
println("score=$score")
println("label=$label")
}
score ← 8
12fun main() {13 val score→ 8 = 8 //@score=3, 1014 val level: Levelif (score >= 8)
16if (score8 >= 8) {17 level = HighLevel()18} else {val label = describe(level)
22val label = describe(level)fun describe(level: Level): String
5fun describe(level: Level): String {6 return when (level) {7 is LowLevel -> "low"8 is HighLevel -> "high"9 }10}label ← high
22 val label→ high = describe(level)2324 println("score=$score8")25 println("label=$labelhigh")26}outputscore=8 label=high
score ← 3
12fun main() {13 val score→ 3 = 314 val level: Levelelse
17 level = HighLevel()18} else {19 level = LowLevel()20}val label = describe(level)
22val label = describe(level)fun describe(level: Level): String
5fun describe(level: Level): String {6 return when (level) {7 is LowLevel -> "low"8 is HighLevel -> "high"9 }10}label ← low
22 val label→ low = describe(level)2324 println("score=$score3")25 println("label=$labellow")26}outputscore=3 label=low
score ← 10
12fun main() {13 val score→ 10 = 1014 val level: Levelif (score >= 8)
16if (score10 >= 8) {17 level = HighLevel()18} else {val label = describe(level)
22val label = describe(level)fun describe(level: Level): String
5fun describe(level: Level): String {6 return when (level) {7 is LowLevel -> "low"8 is HighLevel -> "high"9 }10}label ← high
22 val label→ high = describe(level)2324 println("score=$score10")25 println("label=$labelhigh")26}outputscore=10 label=high