Add requireNotNull with lazy message.
This commit is contained in:
committed by
Ilya Gorbunov
parent
2f02024c24
commit
0717705f15
@@ -41,6 +41,21 @@ public fun <T:Any> requireNotNull(value: T?, message: Any = "Required value was
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Throws an [IllegalArgumentException] with the result of calling [lazyMessage] if the [value] is null. Otherwise
|
||||||
|
* returns the not null value.
|
||||||
|
*
|
||||||
|
* @sample test.collections.PreconditionsTest.requireNotNullWithLazyMessage
|
||||||
|
*/
|
||||||
|
public fun <T:Any> requireNotNull(value: T?, lazyMessage: () -> Any): T {
|
||||||
|
if (value == null) {
|
||||||
|
val message = lazyMessage()
|
||||||
|
throw IllegalArgumentException(message.toString())
|
||||||
|
} else {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Throws an [IllegalStateException] with an optional [message] if the [value] is false.
|
* Throws an [IllegalStateException] with an optional [message] if the [value] is false.
|
||||||
*
|
*
|
||||||
@@ -65,7 +80,7 @@ public inline fun check(value: Boolean, lazyMessage: () -> Any): Unit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Throws an [IllegalArgumentException] with the given [message] if the [value] is null. Otherwise
|
* Throws an [IllegalStateException] with the given [message] if the [value] is null. Otherwise
|
||||||
* returns the not null value.
|
* returns the not null value.
|
||||||
*
|
*
|
||||||
* @sample test.collections.PreconditionsTest.checkNotNull
|
* @sample test.collections.PreconditionsTest.checkNotNull
|
||||||
|
|||||||
@@ -84,6 +84,21 @@ class PreconditionsTest() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
test fun requireNotNullWithLazyMessage() {
|
||||||
|
val error = failsWith(javaClass<IllegalArgumentException>()) {
|
||||||
|
val obj: Any? = null
|
||||||
|
requireNotNull(obj) { "Message" }
|
||||||
|
}
|
||||||
|
assertEquals("Message", error.getMessage())
|
||||||
|
|
||||||
|
var lazyCalled: Boolean = false
|
||||||
|
requireNotNull("not null") {
|
||||||
|
lazyCalled = true
|
||||||
|
"Message"
|
||||||
|
}
|
||||||
|
assertFalse(lazyCalled, "Message is not evaluated if the condition is met")
|
||||||
|
}
|
||||||
|
|
||||||
test fun checkNotNull() {
|
test fun checkNotNull() {
|
||||||
val s1: String? = "S1"
|
val s1: String? = "S1"
|
||||||
val r1: String = checkNotNull(s1)
|
val r1: String = checkNotNull(s1)
|
||||||
|
|||||||
Reference in New Issue
Block a user