Sealed classes have the ability to restrict subclass creation; it has hierarchy which is is fixed. This comes in handy for having a defined number of Subclass Types. In a "when" statement, we typically need a default branch ("else"). In the example below, our subclasses are products. What if we added a new product besides refrigerators and washing machines? The compiler wouldn't know and would always default to our else branch, making an unwanted bug.
//prefix the class with the sealed keyword to indicate the class is sealed
sealed class Product(val modelNo: String) {
constructor() : this("")
}
data class WashingMachine(val capacity: Int, val model: String): Product(model)
data class Refrigerator(val cubicFeet: Long, val model: String): Product(model)
//A great use case for sealed classes is the when statement. It keeps the options limited (no default branch needed)
// to a certain number of subclasses
fun getExcitedAboutProduct(product: Product): String =
when(product)
{
is WashingMachine -> "I mean, does it work quietly???"
is Refrigerator -> "Oh snap, it has a touchscreen!?!"
}
/*
Adding a data new dataclass that extends Product would produce a compiler error, because
our "when" statement does not address all children of the sealed class
*/
fun main(args: Array<String>)
{
println(getExcitedAboutProduct(WashingMachine(33, "ML24A")))
}