com.seeq.utilities.Optionals.kt Maven / Gradle / Ivy
The newest version!
package com.seeq.utilities
import java.util.Optional
/** Convert from Java's Optional to Kotlin's nullable. If the Optional is empty then this function will return null. */
inline val Optional.asNullable: T? get() = this.orElse(null)
/** Convert from a nullable Kotlin value to [Optional], using [Optional.ofNullable]. */
inline val T?.asOptional: Optional get() = Optional.ofNullable(this)
/**
* Helper for conditionally applying a nullable argument to a fluent builder.
* If [x] is `null`, `this` is returned. Otherwise the value is applied to `this.`[fn], returning the updated builder.
*
* ```kt
* fooBuilder
* .withX(x)
* .maybe(y) { withY(it) }
* .withZ(z)
* ```
*/
inline fun A.maybe(x: B?, fn: A.(B) -> A): A = x?.let { this.fn(it) } ?: this