Optional<T> in Kotlin using a Sealed Class

Ken Yee
1 min readApr 12, 2020

Nice quick way to add Guava or Android API24’s Optional<T> using Kotlin’s sealed classes (until they build this into the languate as a Maybe class):

sealed class Option<out A> {
object None : Option<Nothing>()
data class Value<out A>(val value: A) : Option<A>()

companion object {
fun <A>from(value: A?): Option<out A> {
return value?.let { Value(value) } ?: None
}
}
}

Usage is pretty simple…just do Option.from<YourClass> on any value that may be nullable. Then you can use this to pass through a reactive stream since you can’t pass nulls through; on the other wise, unwrap it with:

when (it) {
is Value ->
val value = it.value
is None ->
// handle error
}

--

--

Ken Yee

Mobile (Native Android), Backend (Spring Boot, Quarkus), Devops (Jenkins, Docker, K8s) software engineer. Currently Kotlin All The Things!