All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.io.kotest.fp.Option.kt Maven / Gradle / Ivy

There is a newer version: 4.0.7
Show newest version
package io.kotest.fp

sealed class Option {
   data class Some(val value: T) : Option()
   object None : Option()

   fun isDefined(): Boolean = this is Some
   fun isEmpty(): Boolean = this is None

   inline fun  fold(ifEmpty: () -> R, ifDefined: (T) -> R): R = when (this) {
      is Some -> ifDefined(this.value)
      is None -> ifEmpty()
   }

   inline fun  map(f: (T) -> U): Option = when (this) {
      is None -> this
      is Some -> f(this.value).some()
   }
}

fun  Option.getOrElse(t: T): T = fold({ t }, { it })

fun  Option.getOrElse(f: () -> T): T = fold({ f() }, { it })

fun  Option.orElse(other: Option): Option = when (this) {
   is Option.None -> other
   else -> this
}

fun  Option.orElse(other: () -> Option): Option = when (this) {
   is Option.None -> other()
   else -> this
}

fun  T.some(): Option = Option.Some(this)

fun  Collection.firstOption(): Option = if (this.isEmpty()) Option.None else Option.Some(first())

fun  T?.toOption(): Option = if (this == null) Option.None else Option.Some(
   this
)