https://kotlinlang.org logo
#announcements
Title
# announcements
g

George Pandian

10/28/2019, 11:07 AM
Hi , just wanted to understand what is the main difference between open and sealed class and also the use cases for its usage.
d

diesieben07

10/28/2019, 11:11 AM
An open class can be subclassed by anyone (provided the constructor is accessible). A sealed class can only be subclassed by classes in the same file (or nested classes). This enables exhaustiveness-checking on
when
statements, since you know there will always be a fixed number of subtypes. Sealed classes are also
abstract
by default.
👍 2
s

Stephan Schroeder

10/28/2019, 11:12 AM
open
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.html
👍 1
☝️ 2
g

George Pandian

10/28/2019, 11:21 AM
Thank you so much to both of you. It makes sense.
e

eekboom

10/28/2019, 11:34 AM
I didn’t get sealed classes at first, too. Now I often use them when I would use an Enum, but some enum values need additional data. That can best be understood with an example:
Copy code
sealed 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
}
👍 1
2 Views