fun <R> 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`
}
@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))
}