Add toErrorIfNull & toErrorUnlessNull

Closes #84
This commit is contained in:
Michael Bull 2023-04-03 14:02:06 +01:00
parent c6aeb9619f
commit fd2160c7a6
2 changed files with 110 additions and 0 deletions

View File

@ -189,6 +189,23 @@ public inline fun <V, E> Result<V, E>.toErrorIf(predicate: (V) -> Boolean, trans
}
}
/**
* Returns the supplied [error] if this [Result] is [Ok] and the [value][Ok.value] is `null`,
* otherwise this [Result].
*
* @see [toErrorIf]
*/
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() }
)
}
/**
* Returns the [transformation][transform] of the [value][Ok.value] if this [Result] is [Ok]
* and _does not_ satisfy the given [predicate], otherwise this [Result].
@ -210,3 +227,20 @@ public inline fun <V, E> Result<V, E>.toErrorUnless(predicate: (V) -> Boolean, t
is Err -> this
}
}
/**
* Returns the supplied [error] unless this [Result] is [Ok] and the [value][Ok.value] is `null`,
* otherwise this [Result].
*
* @see [toErrorUnless]
*/
public inline fun <V, E> Result<V, E>.toErrorUnlessNull(error: () -> E): Result<V, E> {
contract {
callsInPlace(error, InvocationKind.AT_MOST_ONCE)
}
return toErrorUnless(
{ it == null },
{ error() }
)
}

View File

@ -2,6 +2,7 @@ package com.github.michaelbull.result
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertSame
class MapTest {
@ -174,4 +175,79 @@ class MapTest {
)
}
}
class ToErrorIfNull {
@Test
fun returnsValueIfOk() {
val result = Ok("a").toErrorIfNull { "b" }
result as Ok
assertEquals(
expected = "a",
actual = result.value
)
}
@Test
fun returnsTransformedErrorIfNull() {
val result = Ok(null).toErrorIfNull { "a" }
result as Err
assertEquals(
expected = "a",
actual = result.error
)
}
@Test
fun returnsErrorIfErr() {
val result = Err("a").toErrorIfNull { "b" }
result as Err
assertEquals(
expected = "a",
actual = result.error
)
}
}
class ToErrorUnlessNull {
@Test
fun returnsTransformedErrorIfNotNull() {
val result = Ok("a").toErrorUnlessNull { "b" }
result as Err
assertEquals(
expected = "b",
actual = result.error
)
}
@Test
fun returnsValueIfNull() {
val result = Ok(null).toErrorUnlessNull { "a" }
result as Ok
assertNull(result.value)
}
@Test
fun returnsErrorIfErr() {
val result = Err("a").toErrorUnlessNull { "b" }
result as Err
assertEquals(
expected = "a",
actual = result.error
)
}
}
}