From: David ‘Bombe’ Roden Date: Fri, 1 Nov 2019 17:33:17 +0000 (+0100) Subject: ✨ Add boolean helper onFalse X-Git-Tag: v81^2~98 X-Git-Url: https://git.pterodactylus.net/?a=commitdiff_plain;h=4e14522463e25ae70756bac80a507d01a772a0c5;p=Sone.git ✨ Add boolean helper onFalse --- diff --git a/src/main/kotlin/net/pterodactylus/sone/utils/Booleans.kt b/src/main/kotlin/net/pterodactylus/sone/utils/Booleans.kt index bfcb319..49deb87 100644 --- a/src/main/kotlin/net/pterodactylus/sone/utils/Booleans.kt +++ b/src/main/kotlin/net/pterodactylus/sone/utils/Booleans.kt @@ -9,3 +9,11 @@ fun Boolean.ifTrue(block: () -> R): R? = if (this) block() else null * Returns the value of [block] if `this` is false, returns `null` otherwise. */ fun Boolean.ifFalse(block: () -> R): R? = if (!this) block() else null + +/** + * Returns `this` but runs the given block if `this` is `false`. + * + * @param block The block to run if `this` is `false` + * @return `this` + */ +fun Boolean.onFalse(block: () -> Unit): Boolean = this.also { if (!this) block() } diff --git a/src/test/kotlin/net/pterodactylus/sone/utils/BooleansTest.kt b/src/test/kotlin/net/pterodactylus/sone/utils/BooleansTest.kt index 56627c3..a1b6da7 100644 --- a/src/test/kotlin/net/pterodactylus/sone/utils/BooleansTest.kt +++ b/src/test/kotlin/net/pterodactylus/sone/utils/BooleansTest.kt @@ -1,9 +1,8 @@ package net.pterodactylus.sone.utils -import org.hamcrest.MatcherAssert.assertThat -import org.hamcrest.Matchers.equalTo -import org.hamcrest.Matchers.nullValue -import org.junit.Test +import org.hamcrest.MatcherAssert.* +import org.hamcrest.Matchers.* +import kotlin.test.* /** * Unit test for [Booleans]. @@ -30,4 +29,24 @@ class BooleansTest { assertThat(true.ifFalse { true }, nullValue()) } + @Test + fun `onFalse returns true on true`() { + assertThat(true.onFalse {}, equalTo(true)) + } + + @Test + fun `onFalse returns false on false`() { + assertThat(false.onFalse {}, equalTo(false)) + } + + @Test + fun `onFalse is not executed on true`() { + assertThat(true.onFalse { throw RuntimeException() }, equalTo(true)) + } + + @Test(expected = RuntimeException::class) + fun `onFalse is executed on false`() { + false.onFalse { throw RuntimeException() } + } + }