George Pandian
10/28/2019, 11:07 AMdiesieben07
10/28/2019, 11:11 AMwhen
statements, since you know there will always be a fixed number of subtypes.
Sealed classes are also abstract
by default.Stephan Schroeder
10/28/2019, 11:12 AMopen
is not related to sealed
! open
is the opposite to Java’s final
keywork -> no subclasses. While in Java the default for a class is to be open (hence you need final
to declare your wish for the class to be non-extendable) the default for Kotlin classes is to be final (hence you need the open
keyword to declare that the class is intended to be subclasses.
sealed
classes lie somewhere between enums and classes (and are sometimes called “enums with superpowers”). You can only subclass from within the same file, hence the compiler knows of all possible subclasses at compile time.
Sealed classes are a non-trivial subject, so it’s better to check the official documentation for those: https://kotlinlang.org/docs/reference/sealed-classes.htmlGeorge Pandian
10/28/2019, 11:21 AMeekboom
10/28/2019, 11:34 AMsealed class Escape {
object Error : Escape() // Exception will be thrown if a character would need to be escaped
object CStyle : Escape() // Escape using cstyle sequences like \t
data class Character(val char: Char) : Escape() // Escape by prefixing with the given characters
}