gojuno / koptional

Minimalistic Optional type for Kotlin that tries to fit its null-safe type system as smooth as possible.
Apache License 2.0
289 stars 21 forks source link

Provide some functional operations #7

Closed debop closed 7 years ago

debop commented 7 years ago

Implementation functional operations for Option like scala, java 8

sealed class Optional<out T : Any> : Serializable {
    val isPresent: Boolean get() = this != None
}

inline fun <T : Any> Iterable<Optional<T>>.foreach(action: (T) -> Unit): Unit =
    this.filter { it.isPresent }.map { (it as Some<T>).value }.forEach(action)

inline fun <T : Any, R> Iterable<Optional<T>>.flatMap(mapper: (T) -> R): List<R> =
    this.filter { it.isPresent }.map { (it as Some<T>).value }.map(mapper)
artem-zinnatullin commented 7 years ago

We intentionally didn't add such operations because Kotlin already has them in stdlib.

In particular isPresent() can be replaced with is Some which is shorter btw :)

Please see #6 for explanation.