简体   繁体   中英

What does the sealed modifier represent in Kotlin?

I am little confused about the use of the sealed modifier.

What does it do?

The official docs cover this.

Sealed classes have restricted inheritance hierarchies: only classes that are declared inside them or are in the same file as them (since Kotlin 1.1) can be subclasses of a sealed class.

This can be useful when combined with when expressions, which can guarantee that their branches exhaustively check the possible subclasses of a sealed class.

This modifier is mainly use when you want to restrict the possibility of creating a subclass, it means all direct subclasses should be nested, this is an example:

sealed class Animal {
    class Cow(val name: String) : Animal()
}

//It generates a compilation error
class Horse : Animal() {
}

So, sealed classes can not have inheritors outside the class.

The other answers are good, but an important point I think that's worth adding: classes that extend subclasses of a sealed class can be placed anywhere, not necessarily in the same file. That's important to note, since a sealed class doesn't necessarily mean that an entire inheritance hierarchy will be in the same file unless every subclass is also sealed .

You can read more about this in the official docs for sealed classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM