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:
parent
dc4101b8ef
commit
f0fb536516
@ -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)
|
||||
* - 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 Error<out E> constructor(val error: E) : Result<Nothing, E>()
|
||||
|
Loading…
Reference in New Issue
Block a user