-1

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

What does it do?

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
  • Try [this link](https://kotlinlang.org/docs/reference/sealed-classes.html) - the `sealed` keyword, as far as classes go, ensures that all subclasses of a class are in the same file and nested with the super class. – josephmbustamante Jun 15 '17 at 13:40
  • 2
    What's unclear about the documentation? – nhaarman Jun 15 '17 at 13:43

3 Answers3

6

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.

zsmb13
  • 85,752
  • 11
  • 221
  • 226
3

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.

  • 5
    That's not completely true: Kotlin 1.1 lifted the restriction, and now the subclasses can be located outside the `sealed` class, but should be placed in the same file. – hotkey Jun 15 '17 at 13:41
  • Also, it's worth mentioning what is the profit of this restriction: the compiler can check that a `when` statement has all the subtypes listed in its branches, thus not requiring an `else` branch. – hotkey Jun 15 '17 at 13:45
  • 1
    In the >=1.1 REPL, subclasses must still be nested inside – shanethehat Jun 15 '17 at 13:56
2

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.