Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[result4k] Introduce a way to early return on successful result with a null value #67

Merged
merged 1 commit into from
Aug 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,10 @@ fun <T, E> Result<T, E>.failureOrNull(): E? = when (this) {
is Success<T> -> null
is Failure<E> -> reason
}

/**
* Convert a `Success` of a nullable value to a `Success` of a non-null value, or calling `block` to abort from
* the current function if the value is `null`
*/
inline fun <T, E> Result<T?, E>.onNull(block: () -> Nothing): Result<T, E> =
flatMap { if (it != null) Success(it) else block() }
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package dev.forkhandles.result4k

import org.junit.jupiter.api.Test
import kotlin.test.assertEquals

class OnNullTests {

@Test
fun `does nothing on successful non-null result`() {
fun subject() = Success("non-null")
.onNull { return Success("early-returned") }

assertEquals(Success("non-null"), subject())
}

@Test
fun `does nothing on unsuccessful result`() {
fun subject() = resultFrom { throw AnError("kaboom"); "unreachable" }
.onNull { return Success("early-returned") }

assertEquals(Failure(AnError("kaboom")), subject())
}

@Test
fun `early returns on successful null result`() {
fun subject() = Success(null)
.onNull { return Success("early-returned") }
.map { "mapped" }

assertEquals(Success("early-returned"), subject())
}

@Test
fun `continue the chain on successful non-null result`() {
fun subject() = Success("non-null")
.onNull { return Success("early-returned") }
.map { "mapped" }

assertEquals(Success("mapped"), subject())
}
}

private data class AnError(override val message: String) : Exception(message)
Loading