Improve type constraint on toErrorIfNull

Closes #84 and closes #86
This commit is contained in:
Kirill Zhukov 2023-05-09 12:29:31 -07:00 committed by Michael Bull
parent ebe8f33a1b
commit d7dbf35bcf
3 changed files with 24 additions and 11 deletions

View File

@ -223,6 +223,11 @@ subprojects {
name.set("Matthias Geisler") name.set("Matthias Geisler")
url.set("https://github.com/bitPogo") url.set("https://github.com/bitPogo")
} }
contributor {
name.set("Kirill Zhukov")
url.set("https://github.com/kirillzh")
}
} }
scm { scm {

View File

@ -195,15 +195,19 @@ public inline fun <V, E> Result<V, E>.toErrorIf(predicate: (V) -> Boolean, trans
* *
* @see [toErrorIf] * @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 { contract {
callsInPlace(error, InvocationKind.AT_MOST_ONCE) callsInPlace(error, InvocationKind.AT_MOST_ONCE)
} }
return toErrorIf( return when (this) {
{ it == null }, is Ok -> if(value == null) {
{ error() } Err(error())
) } else {
Ok(value)
}
is Err -> this
}
} }
/** /**
@ -239,8 +243,12 @@ public inline fun <V, E> Result<V, E>.toErrorUnlessNull(error: () -> E): Result<
callsInPlace(error, InvocationKind.AT_MOST_ONCE) callsInPlace(error, InvocationKind.AT_MOST_ONCE)
} }
return toErrorUnless( return when (this) {
{ it == null }, is Ok -> if (value == null) {
{ error() } this
) } else {
Err(error())
}
is Err -> Err(error())
}
} }

View File

@ -192,7 +192,7 @@ class MapTest {
@Test @Test
fun returnsTransformedErrorIfNull() { fun returnsTransformedErrorIfNull() {
val result = Ok(null).toErrorIfNull { "a" } val result: Result<Nothing, String> = Ok(null).toErrorIfNull { "a" }
result as Err result as Err
@ -245,7 +245,7 @@ class MapTest {
result as Err result as Err
assertEquals( assertEquals(
expected = "a", expected = "b",
actual = result.error actual = result.error
) )
} }