Skip to content

Commit

Permalink
Add toErrorIfNull & toErrorUnlessNull
Browse files Browse the repository at this point in the history
Closes #84
  • Loading branch information
michaelbull committed Apr 3, 2023
1 parent c6aeb96 commit fd2160c
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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].
Expand All @@ -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() }
)
}
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
import kotlin.test.assertSame

class MapTest {
Expand Down Expand Up @@ -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
)
}
}
}

0 comments on commit fd2160c

Please sign in to comment.