* Returns the value of [block] if `this` is false, returns `null` otherwise.
*/
fun <R> 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() }
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].
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() }
+ }
+
}