From: David ‘Bombe’ Roden Date: Sat, 4 Jan 2020 23:40:52 +0000 (+0100) Subject: ✨ Add onTrue method for Booleans X-Git-Tag: v81^2~5^2~16 X-Git-Url: https://git.pterodactylus.net/?a=commitdiff_plain;h=2bc7c56a3c7a138b771909682d41347bd89064c8;p=Sone.git ✨ Add onTrue method for Booleans --- 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)) }