From 2bc7c56a3c7a138b771909682d41347bd89064c8 Mon Sep 17 00:00:00 2001 From: =?utf8?q?David=20=E2=80=98Bombe=E2=80=99=20Roden?= Date: Sun, 5 Jan 2020 00:40:52 +0100 Subject: [PATCH] =?utf8?q?=E2=9C=A8=20Add=20onTrue=20method=20for=20Boolea?= =?utf8?q?ns?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- .../kotlin/net/pterodactylus/sone/utils/Booleans.kt | 8 ++++++++ .../net/pterodactylus/sone/utils/BooleansTest.kt | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/main/kotlin/net/pterodactylus/sone/utils/Booleans.kt b/src/main/kotlin/net/pterodactylus/sone/utils/Booleans.kt index 49deb87..1d3e097 100644 --- a/src/main/kotlin/net/pterodactylus/sone/utils/Booleans.kt +++ b/src/main/kotlin/net/pterodactylus/sone/utils/Booleans.kt @@ -11,6 +11,14 @@ fun Boolean.ifTrue(block: () -> R): R? = if (this) block() else null fun Boolean.ifFalse(block: () -> R): R? = if (!this) block() else null /** + * Returns `this` but runs the given block if `this` is `true`. + * + * @param block The block to run if `this` is `true` + * @return `this` + */ +fun Boolean.onTrue(block: () -> Unit): Boolean = also { if (this) block() } + +/** * Returns `this` but runs the given block if `this` is `false`. * * @param block The block to run if `this` is `false` diff --git a/src/test/kotlin/net/pterodactylus/sone/utils/BooleansTest.kt b/src/test/kotlin/net/pterodactylus/sone/utils/BooleansTest.kt index a1b6da7..bd81f08 100644 --- a/src/test/kotlin/net/pterodactylus/sone/utils/BooleansTest.kt +++ b/src/test/kotlin/net/pterodactylus/sone/utils/BooleansTest.kt @@ -30,6 +30,26 @@ class BooleansTest { } @Test + fun `onTrue returns true on true`() { + assertThat(true.onTrue {}, equalTo(true)) + } + + @Test + fun `onTrue returns false on false`() { + assertThat(false.onTrue {}, equalTo(false)) + } + + @Test + fun `onTrue is not executed on false`() { + assertThat(false.onTrue { throw RuntimeException() }, equalTo(false)) + } + + @Test(expected = RuntimeException::class) + fun `onTrue is executed on true`() { + true.onTrue { throw RuntimeException() } + } + + @Test fun `onFalse returns true on true`() { assertThat(true.onFalse {}, equalTo(true)) } -- 2.7.4