Add helper for booleans
authorDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Thu, 31 Aug 2017 19:29:53 +0000 (21:29 +0200)
committerDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Fri, 1 Sep 2017 20:45:25 +0000 (22:45 +0200)
src/main/kotlin/net/pterodactylus/sone/utils/Booleans.kt [new file with mode: 0644]
src/test/kotlin/net/pterodactylus/sone/utils/BooleansTest.kt [new file with mode: 0644]

diff --git a/src/main/kotlin/net/pterodactylus/sone/utils/Booleans.kt b/src/main/kotlin/net/pterodactylus/sone/utils/Booleans.kt
new file mode 100644 (file)
index 0000000..3202b82
--- /dev/null
@@ -0,0 +1,6 @@
+package net.pterodactylus.sone.utils
+
+/**
+ * Returns the value of [block] if `this` is true, returns `null` otherwise.
+ */
+fun <R> Boolean.ifTrue(block: () -> R): R? = if (this) block() else null
diff --git a/src/test/kotlin/net/pterodactylus/sone/utils/BooleansTest.kt b/src/test/kotlin/net/pterodactylus/sone/utils/BooleansTest.kt
new file mode 100644 (file)
index 0000000..5e5ce51
--- /dev/null
@@ -0,0 +1,23 @@
+package net.pterodactylus.sone.utils
+
+import org.hamcrest.MatcherAssert.assertThat
+import org.hamcrest.Matchers.equalTo
+import org.hamcrest.Matchers.nullValue
+import org.junit.Test
+
+/**
+ * Unit test for [Booleans].
+ */
+class BooleansTest {
+
+       @Test
+       fun `ifTrue is executed if boolean is true`() {
+               assertThat(true.ifTrue { true }, equalTo(true))
+       }
+
+       @Test
+       fun `ifTrue is not executed if boolean is false`() {
+               assertThat(false.ifTrue { true }, nullValue())
+       }
+
+}