KT-20357: Add a sample for requireNotNull
This commit is contained in:
@@ -27,6 +27,31 @@ class Preconditions {
|
|||||||
assertPrints(getIndices(3), "[1, 2, 3]")
|
assertPrints(getIndices(3), "[1, 2, 3]")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Sample
|
||||||
|
fun failRequireNotNullWithLazyMessage() {
|
||||||
|
|
||||||
|
fun printRequiredParam(params: Map<String, String?>) {
|
||||||
|
val required: String = requireNotNull(params["required"]) { "Required value must be non-null" } // returns a non-null value
|
||||||
|
println(required)
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
|
||||||
|
fun printRequiredParamByUpperCase(params: Map<String, String?>) {
|
||||||
|
val requiredParam: String? = params["required"]
|
||||||
|
requireNotNull(requiredParam) { "Required value must be non-null" }
|
||||||
|
// now requiredParam is smartcast to String so that it is unnecessary to use the safe call(?.)
|
||||||
|
println(requiredParam.toUpperCase())
|
||||||
|
}
|
||||||
|
|
||||||
|
val params: MutableMap<String, String?> = mutableMapOf("required" to null)
|
||||||
|
assertFailsWith<IllegalArgumentException> { printRequiredParam(params) }
|
||||||
|
assertFailsWith<IllegalArgumentException> { printRequiredParamByUpperCase(params) }
|
||||||
|
|
||||||
|
params["required"] = "non-empty-param"
|
||||||
|
printRequiredParam(params) // prints "non-empty-param"
|
||||||
|
printRequiredParamByUpperCase(params) // prints "NON-EMPTY-PARAM"
|
||||||
|
}
|
||||||
|
|
||||||
@Sample
|
@Sample
|
||||||
fun failCheckWithLazyMessage() {
|
fun failCheckWithLazyMessage() {
|
||||||
|
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ public inline fun <T : Any> requireNotNull(value: T?): T {
|
|||||||
* Throws an [IllegalArgumentException] with the result of calling [lazyMessage] if the [value] is null. Otherwise
|
* Throws an [IllegalArgumentException] with the result of calling [lazyMessage] if the [value] is null. Otherwise
|
||||||
* returns the not null value.
|
* returns the not null value.
|
||||||
*
|
*
|
||||||
* @sample samples.misc.Preconditions.failRequireWithLazyMessage
|
* @sample samples.misc.Preconditions.failRequireNotNullWithLazyMessage
|
||||||
*/
|
*/
|
||||||
@kotlin.internal.InlineOnly
|
@kotlin.internal.InlineOnly
|
||||||
public inline fun <T : Any> requireNotNull(value: T?, lazyMessage: () -> Any): T {
|
public inline fun <T : Any> requireNotNull(value: T?, lazyMessage: () -> Any): T {
|
||||||
|
|||||||
Reference in New Issue
Block a user