Skip to content

Commit

Permalink
Legg til orDefault med funksjon som input (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
bjerga authored Dec 15, 2023
1 parent 6482eb7 commit bb0372d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package no.nav.helsearbeidsgiver.utils.pipe
fun <T : Any> T?.orDefault(default: T): T =
this ?: default

fun <T : Any> T?.orDefault(block: () -> T): T =
this ?: block()

fun Boolean.ifTrue(block: () -> Unit): Boolean =
also { if (this) block() }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,32 @@ import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe

class PipeUtilsKtTest : FunSpec({
test("orDefault returns receiver if non-null or default otherwise") {
val nullableStringThatIsNull: String? = null
context("orDefault") {
test("'orDefault(default)' returns receiver if non-null or default otherwise") {
val nullableStringThatIsNull: String? = null

@Suppress("RedundantNullableReturnType")
val nullableStringThatIsNotNull: String? = "I may be null. Who knows?"
@Suppress("RedundantNullableReturnType")
val nullableStringThatIsNotNull: String? = "I may be null. Who knows?"

@Suppress("RedundantExplicitType")
val nonNullableString: String = "I am definitely not null!"
@Suppress("RedundantExplicitType")
val nonNullableString: String = "I am definitely not null!"

nullableStringThatIsNull.orDefault(nonNullableString) shouldBe nonNullableString
nullableStringThatIsNotNull.orDefault(nonNullableString) shouldBe nullableStringThatIsNotNull
nullableStringThatIsNull.orDefault(nonNullableString) shouldBe nonNullableString
nullableStringThatIsNotNull.orDefault(nonNullableString) shouldBe nullableStringThatIsNotNull
}

test("'orDefault(block)' returns receiver if non-null or block() otherwise") {
val nullableIntThatIsNull: Int? = null

@Suppress("RedundantNullableReturnType")
val nullableIntThatIsNotNull: Int? = -42

@Suppress("RedundantExplicitType")
val nonNullableInt: Int = 1337

nullableIntThatIsNull.orDefault { nonNullableInt } shouldBe nonNullableInt
nullableIntThatIsNotNull.orDefault { nonNullableInt } shouldBe nullableIntThatIsNotNull
}
}

test("ifTrue executes block if receiver is 'true'") {
Expand Down

0 comments on commit bb0372d

Please sign in to comment.