From 4e14522463e25ae70756bac80a507d01a772a0c5 Mon Sep 17 00:00:00 2001 From: =?utf8?q?David=20=E2=80=98Bombe=E2=80=99=20Roden?= Date: Fri, 1 Nov 2019 18:33:17 +0100 Subject: [PATCH] =?utf8?q?=E2=9C=A8=20Add=20boolean=20helper=20onFalse?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- .../net/pterodactylus/sone/utils/Booleans.kt | 8 +++++++ .../net/pterodactylus/sone/utils/BooleansTest.kt | 27 ++++++++++++++++++---- 2 files changed, 31 insertions(+), 4 deletions(-) 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() } + } + } -- 2.7.4