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")
url.set("https://github.com/bitPogo")
}
contributor {
name.set("Kirill Zhukov")
url.set("https://github.com/kirillzh")
}
}
scm {

View File

@ -195,15 +195,19 @@ 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() }
)
return when (this) {
is Ok -> if(value == null) {
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)
}
return toErrorUnless(
{ it == null },
{ error() }
)
return when (this) {
is Ok -> if (value == null) {
this
} else {
Err(error())
}
is Err -> Err(error())
}
}

View File

@ -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
@ -245,7 +245,7 @@ class MapTest {
result as Err
assertEquals(
expected = "a",
expected = "b",
actual = result.error
)
}