fun <T> T?.asList() = this?.let(::listOf) ?: emptyList<T>()
val Any?.unit get() = Unit
+
+fun <T> T?.throwOnNullIf(throwCondition: Boolean, exception: () -> Throwable) =
+ if (this == null && throwCondition) throw exception() else this
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
/**
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))
+ }
+
}