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

com.natpryce.nullables.kt Maven / Gradle / Ivy

There is a newer version: 2.0.0
Show newest version
package com.natpryce

/*
 * Translate between the Result and Nullable/Optional/Maybe monads
 */

/**
 * Convert a nullable value to a Result, using the result of the errorSupplier as the error reason if the value is null.
 */
inline fun  T?.asResultOr(errorSupplier: () -> E) =
    if (this != null) Ok(this) else Err(errorSupplier())

/**
 * Returns the success value, or null if the Result is an error.
 */
fun  Result.valueOrNull() = when (this) {
    is Ok -> value
    is Err -> null
}

/**
 * Returns the error reason, or null if the Result is a success.
 */
fun  Result.errorOrNull() = when (this) {
    is Ok -> null
    is Err -> reason
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy