Detailed information can be found in official document.
Sealed classes and interfaces | Kotlin
Sealed classes are similar to enum classes: the set of values for an enum type is also restricted, but each enum constant exists only as a single instance, whereas a subclass of a sealed class can have multiple instances, each with its own state.
object
to create single instance in sealed class.sealed interface Error
sealed class IOError(): Error
class FileReadError(val file: File): IOError()
class DatabaseError(val source: DataSource): IOError()
object RuntimeError : Error
A sealed class is abstract by itself, it cannot be instantiated directly and can have abstract
members.
If the statement covers all cases, we don't need to add an else
clause to the statement.
// to define two new subhierarchies
sealed interface DinnerMenu
sealed interface LunchMenu
sealed class Menu {
// resticting the Menu hieararchy to LaunchMenu and DinnerMenu
data class PIZZA(val name: String, val size: String, val quantity: Int): Menu(), DinnerMenu
data class BURGER(val quantity: Int, val size: String): Menu(), LunchMenu
data class CHICKEN(val quantity: Int, val pieces: String): Menu(), LunchMenu
}