Sealed class in Kotlin

Level 4230 keystrokes

A sealed class has a closed set of subclasses known at compile time. Because of that, a when over it can cover every case without else, and each is-check smart-casts r, so r.data and r.msg can be used.

Kotlin code

// sealed: subclasses must be declared in the same package and module, so the set is closed
1sealed class Result
// Subclass for a successful result, holding data
2data class Success(val data: String) : Result()
// Subclass for a failure, holding an error message
3data class Error(val msg: String) : Result()
4
// when is exhaustive over the sealed class, so no else branch is needed
5fun handle(r: Result) = when (r) {
// is checks the type and smart-casts r to Success, so r.data is accessible
6 is Success -> println(r.data)
// Same for Error: r.msg is accessible
7 is Error -> println(r.msg)
8}
9
// The Success branch runs: prints OK
10handle(Success("OK"))

Output

OK
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • (× 10
  • )× 10
  • :× 5
  • -× 2
  • .× 2
  • "× 2
  • >× 2
  • {× 1
  • }× 1
  • =× 1

More Kotlin examples at level 4

← Kotlin typing practice