Add Result.of factory method

Inspired by result4k, invokes a callback within a try/catch block,
returning an Error if an exception was thrown and Ok otherwise.
This commit is contained in:
Michael Bull 2017-10-22 15:08:23 +01:00
parent dc4101b8ef
commit f0fb536516

View File

@ -7,7 +7,22 @@ package com.github.michaelbull.result
* - Haskell: [Data.Either](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html) * - Haskell: [Data.Either](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html)
* - Rust: [Result](https://doc.rust-lang.org/std/result/enum.Result.html) * - Rust: [Result](https://doc.rust-lang.org/std/result/enum.Result.html)
*/ */
sealed class Result<out V, out E> sealed class Result<out V, out E> {
companion object {
/**
* Invokes a [function] and wraps it in a [Result], returning an [Error] if a [Throwable]
* was thrown, otherwise [Ok].
*/
inline fun <T> of(function: () -> T): Result<T, Throwable> {
return try {
Ok(function.invoke())
} catch (t: Throwable) {
Error(t)
}
}
}
}
data class Ok<out V> constructor(val value: V) : Result<V, Nothing>() data class Ok<out V> constructor(val value: V) : Result<V, Nothing>()
data class Error<out E> constructor(val error: E) : Result<Nothing, E>() data class Error<out E> constructor(val error: E) : Result<Nothing, E>()