From: David ‘Bombe’ Roden Date: Fri, 22 Feb 2019 13:42:15 +0000 (+0100) Subject: Add method to throw no null if condition is met X-Git-Tag: v79^2~107^2~4 X-Git-Url: https://git.pterodactylus.net/?p=Sone.git;a=commitdiff_plain;h=5ef06b540267732918fa2119c8d9536ef81b0dfd Add method to throw no null if condition is met --- diff --git a/src/main/kotlin/net/pterodactylus/sone/utils/Objects.kt b/src/main/kotlin/net/pterodactylus/sone/utils/Objects.kt index cd36ec9..2f7bd6e 100644 --- a/src/main/kotlin/net/pterodactylus/sone/utils/Objects.kt +++ b/src/main/kotlin/net/pterodactylus/sone/utils/Objects.kt @@ -2,3 +2,6 @@ package net.pterodactylus.sone.utils fun T?.asList() = this?.let(::listOf) ?: emptyList() val Any?.unit get() = Unit + +fun T?.throwOnNullIf(throwCondition: Boolean, exception: () -> Throwable) = + if (this == null && throwCondition) throw exception() else this diff --git a/src/test/kotlin/net/pterodactylus/sone/utils/ObjectsTest.kt b/src/test/kotlin/net/pterodactylus/sone/utils/ObjectsTest.kt index 1c2d7f5..9e96bfe 100644 --- a/src/test/kotlin/net/pterodactylus/sone/utils/ObjectsTest.kt +++ b/src/test/kotlin/net/pterodactylus/sone/utils/ObjectsTest.kt @@ -1,8 +1,7 @@ package net.pterodactylus.sone.utils import org.hamcrest.MatcherAssert.assertThat -import org.hamcrest.Matchers.contains -import org.hamcrest.Matchers.empty +import org.hamcrest.Matchers.* import org.junit.Test /** @@ -20,4 +19,26 @@ class ObjectsTest { assertThat(null.asList(), empty()) } + @Test(expected = IllegalArgumentException::class) + fun `exception is thrown for null and true condition`() { + null.throwOnNullIf(true) { IllegalArgumentException() } + } + + @Test + fun `exception is not thrown for null and false condition`() { + assertThat(null.throwOnNullIf(false) { IllegalArgumentException() }, nullValue()) + } + + @Test + fun `exception is not thrown for any and true condition`() { + val any = Any() + assertThat(any.throwOnNullIf(true) { IllegalArgumentException() }, equalTo(any)) + } + + @Test + fun `exception is not thrown for any and false condition`() { + val any = Any() + assertThat(any.throwOnNullIf(false) { IllegalArgumentException() }, equalTo(any)) + } + }