Generic sealed class in Kotlin

Level 5420 keystrokes

Result<out T> is a sealed hierarchy with Success, Error and Loading nested inside it. Thanks to out (covariance), Result<Nothing> is a subtype of every Result<T>, and because the hierarchy is sealed, when covers all cases without else.

Kotlin code

// sealed with a covariant type parameter: out T means T is only produced, never consumed
1sealed class Result<out T> {
// Success carries data of type T
2 data class Success<T>(val data: T) : Result<T>()
// Result<Nothing> fits any Result<T> because of out
3 data class Error(val message: String) : Result<Nothing>()
// A state without data needs only one instance, so it is an object
4 object Loading : Result<Nothing>()
5}
6
// when covers every subclass, so no else is needed
7fun handle(r: Result<String>) = when (r) {
// Smart cast: r.data is a String here
8 is Result.Success -> println("Data: ${r.data}")
// Smart cast to Error gives access to r.message
9 is Result.Error -> println("Error: ${r.message}")
// An object is compared by identity, so no is is needed
10 Result.Loading -> println("Loading...")
11}
12
// Print Data: Hello
13handle(Result.Success("Hello"))
// Print Error: Failed
14handle(Result.Error("Failed"))

Output

Data: Hello
Error: Failed
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.

  • (× 14
  • )× 14
  • .× 10
  • "× 10
  • >× 9
  • :× 8
  • <× 6
  • {× 4
  • }× 4
  • -× 3

More Kotlin examples at level 5

← Kotlin typing practice