Skip to content

Commit

Permalink
Add transpose
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelbull committed Mar 9, 2024
1 parent aca9ad9 commit c46a292
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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].
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit c46a292

Please sign in to comment.