Michael Bull 2024-03-09 00:22:51 +00:00
parent aca9ad92f8
commit c46a2925b1
2 changed files with 50 additions and 0 deletions

View File

@ -45,6 +45,25 @@ public inline infix fun <V, U> Result<V, Throwable>.mapCatching(transform: (V) -
}
}
/**
* Transposes this [Result<V?, E>][Result] to [Result<V, E>][Result].
*
* Returns null if this [Result] is [Ok] and the [value][Ok.value] is `null`, otherwise this [Result].
*
* - Rust: [Result.transpose][https://doc.rust-lang.org/std/result/enum.Result.html#method.transpose]
*/
public inline fun <V, E> Result<V?, E>.transpose(): Result<V, E>? {
return when (this) {
is Ok -> if (value == null) {
null
} else {
Ok(value)
}
is Err -> this
}
}
/**
* Maps this [Result<Result<V, E>, E>][Result] to [Result<V, E>][Result].
*

View File

@ -2,6 +2,7 @@ package com.github.michaelbull.result
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class MapTest {
private sealed interface MapErr {
@ -76,6 +77,36 @@ class MapTest {
}
}
class Transpose {
@Test
fun returnsNullIfValueIsNull() {
val result = Ok(null)
assertNull(result.transpose())
}
@Test
fun returnsOkIfValueIsNotNull() {
val result = Ok("non null")
assertEquals(
expected = Ok("non null"),
actual = result.transpose()
)
}
@Test
fun returnsErrIfErr() {
val result = Err("non null error")
assertEquals(
expected = Err("non null error"),
actual = result.transpose()
)
}
}
class Flatten {
@Test