Skip to content

Commit

Permalink
legger til to hjelpefunksjoner
Browse files Browse the repository at this point in the history
  • Loading branch information
davidsteinsland committed Nov 5, 2024
1 parent e6bdc33 commit 0d94bc8
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ sealed interface Result<out T> {
data class Error(val error: String, val cause: Throwable? = null) : Result<Nothing>
}

fun <T> Result<T>.getOrThrow() = when (this) {
is Result.Error -> throw RuntimeException(error, cause)
is Result.Ok -> value
}

fun <T, R> Result<T>.map(whenOk: (T) -> Result<R>) = when (this) {
is Result.Error -> this
is Result.Ok -> whenOk(value)
Expand All @@ -18,6 +23,14 @@ fun <T, R> Result<T>.fold(
is Result.Ok -> whenOk(value)
}

fun <R> tryCatch(block: () -> R): Result<R> {
return try {
block().ok()
} catch (err: Exception) {
err.error(err.message.toString())
}
}

fun <T> List<Result<T>>.flatten(): Result<List<T>> {
return fold(Result.Ok(emptyList<T>()) as Result<List<T>>) { acc, result ->
result.fold(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.github.navikt.tbd_libs.result_object

import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.Test

class ResultTest {
Expand Down Expand Up @@ -89,6 +90,31 @@ class ResultTest {
}
}

@Test
fun `get or throw`() {
assertThrows<RuntimeException> {
"Error msg".error().getOrThrow()
}.also { assertEquals("Error msg", it.message) }

assertEquals("Hei", "Hei".ok().getOrThrow())
}

@Test
fun tryCatching() {
tryCatch {
"Hei, på deg!"
}.also {
it as Result.Ok
assertEquals("Hei, på deg!", it.value)
}
tryCatch<String> {
error("Whoops!")
}.also {
it as Result.Error
assertEquals("Whoops!", it.error)
}
}

private fun testfun(feil: Boolean): Result<Testobject> {
return when (feil) {
true -> Result.Error("Denne gir feil altså!")
Expand Down

0 comments on commit 0d94bc8

Please sign in to comment.