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 consumed1sealed class Result<out T> { // Success carries data of type T2 data class Success<T>(val data: T) : Result<T>() // Result<Nothing> fits any Result<T> because of out3 data class Error(val message: String) : Result<Nothing>() // A state without data needs only one instance, so it is an object4 object Loading : Result<Nothing>()5}6 // when covers every subclass, so no else is needed7fun handle(r: Result<String>) = when (r) { // Smart cast: r.data is a String here8 is Result.Success -> println("Data: ${r.data}") // Smart cast to Error gives access to r.message9 is Result.Error -> println("Error: ${r.message}") // An object is compared by identity, so no is is needed10 Result.Loading -> println("Loading...")11}12 // Print Data: Hello13handle(Result.Success("Hello"))// Print Error: Failed14handle(Result.Error("Failed"))Output
Data: Hello Error: Failed
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