Skip to content

Commit

Permalink
toErrorIfNull to return Result with non-null value.
Browse files Browse the repository at this point in the history
  • Loading branch information
Kirill Zhukov committed May 9, 2023
1 parent ebe8f33 commit 157e1ac
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -195,15 +195,18 @@ public inline fun <V, E> Result<V, E>.toErrorIf(predicate: (V) -> Boolean, trans
*
* @see [toErrorIf]
*/
public inline fun <V, E> Result<V, E>.toErrorIfNull(error: () -> E): Result<V, E> {
public inline fun <V, E> Result<V?, E>.toErrorIfNull(error: () -> E): Result<V, E> {
contract {
callsInPlace(error, InvocationKind.AT_MOST_ONCE)
}

return toErrorIf(
{ it == null },
{ error() }
)
).map {
@Suppress("UNCHECKED_CAST")
it as V
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ class MapTest {

@Test
fun returnsTransformedErrorIfNull() {
val result = Ok(null).toErrorIfNull { "a" }
val result: Result<Nothing, String> = Ok(null).toErrorIfNull { "a" }

result as Err

Expand Down

0 comments on commit 157e1ac

Please sign in to comment.