Android Developers
Published in

Android Developers

Sealed with a class

Kotlin Vocabulary — Sealed Classes

The basics of sealed classes

// Result.ktsealed class Result<out T : Any> {
data class Success<out T : Any>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
}
Cannot access ‘<init>’: it is private in Result

Forgetting a branch?

when(result) {
is Result.Success -> { }
is Result.Error -> { }
}
sealed class Result<out T : Any> {
data class Success<out T : Any>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
object InProgress : Result<Nothing>()
}
val action = when(result) {
is Result.Success -> { }
is Result.Error -> { }
}
val <T> T.exhaustive: T
get() = this
when(result){
is Result.Success -> { }
is Result.Error -> { }
}.exhaustive

IDE auto-complete

sealed class Result<out T : Any> {
data class Success<out T : Any>(val data: T) : Result<T>()
sealed class Error(val exception: Exception) : Result<Nothing>() {
class RecoverableError(exception: Exception) : Error(exception)
class NonRecoverableError(exception: Exception) :
Error(exception)
}
object InProgress : Result<Nothing>()
}

Under the hood

sealed class Result
data class Success(val data: Any) : Result()
data class Error(val exception: Exception) : Result()
@Metadata(

d2 = {“Lio/testapp/Result;”, “T”, “”, “()V”, “Error”, “Success”, “Lio/testapp/Result$Success;”, “Lio/testapp/Result$Error;” …}
)
public abstract class Result {
private Result() {}
// $FF: synthetic method
public Result(DefaultConstructorMarker $constructor_marker) {
this();
}
}
  • A private default constructor
  • A synthetic constructor that can only be used by the Kotlin compiler
public final class Success extends Result {
@NotNull
private final Object data

public Success(@NotNull Object data) {

super((DefaultConstructorMarker)null);
this.data = data;
}

--

--

Articles on modern tools and resources to help you build experiences that people love, faster and easier, across every Android device.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store