Last active
November 3, 2016 08:30
-
-
Save stepango/f94b6e8e334d4bc2d7f069b47631a5a8 to your computer and use it in GitHub Desktop.
Mimic Java8 Optional class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.NoSuchElementException | |
sealed class Optional<T : Any>(private val value: T?) { | |
constructor() : this(null) | |
fun get(): T { | |
value ?: throw NoSuchElementException("No value present") | |
return value | |
} | |
val isPresent: Boolean | |
get() = value != null | |
fun ifPresent(consumer: (T) -> Unit) { | |
value?.let { consumer(value) } | |
} | |
fun filter(predicate: (T) -> Boolean): Optional<T> | |
= value?.let { if (predicate(it)) this else empty<T>() } ?: this | |
fun <U : Any> map(mapper: (T) -> U): Optional<U> | |
= value?.let { Optional.ofNullable(mapper(it)) } ?: empty<U>() | |
fun <U : Any> flatMap(mapper: (T) -> Optional<U>): Optional<U> | |
= value?.let { mapper(it) } ?: empty<U>() | |
fun orElse(other: T): T = value ?: other | |
fun orElseGet(other: () -> T): T = value ?: other() | |
fun <X : Throwable> orElseThrow(exceptionSupplier: () -> X): T | |
= value ?: throw exceptionSupplier() | |
override fun equals(other: Any?): Boolean = when { | |
this === other -> true | |
other !is Optional<*> -> false | |
else -> value == other.value | |
} | |
override fun toString(): String = value?.let { "Optional[$value]" } ?: "Optional.EMPTY" | |
override fun hashCode(): Int = value?.hashCode() ?: 0 | |
object EMPTY : Optional<Nothing>() | |
class Some<T : Any>(value: T) : Optional<T>(value) | |
companion object { | |
@Suppress("UNCHECKED_CAST") | |
fun <T : Any> empty(): Optional<T> = EMPTY as Optional<T> | |
fun <T : Any> of(value: T): Optional<T> = Some(value) | |
fun <T : Any> ofNullable(value: T?): Optional<T> = value?.let { of(it) } ?: empty<T>() | |
} | |
class OptionalImpl<T : Any> : Optional<T>() | |
} | |
fun <T : Any> T?.toOptional() = Optional.ofNullable(this) | |
fun <T : Any> Optional<T>.orNull(): T? = if (isPresent) get() else null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment