requireNotNull
Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
fun <T : Any> requireNotNull(value: T?): T
Throws an IllegalArgumentException if the value is null. Otherwise returns the not null value.
Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
inline fun <T : Any> requireNotNull( value: T?, lazyMessage: () -> Any ): T
Throws an IllegalArgumentException with the result of calling lazyMessage if the value is null. Otherwise returns the not null value.
import kotlin.test.*
fun main(args: Array<String>) {
//sampleStart
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.uppercase())
}
val params: MutableMap<String, String?> = mutableMapOf("required" to null)
// printRequiredParam(params) // will fail with IllegalArgumentException
// printRequiredParamByUpperCase(params) // will fail with IllegalArgumentException
params["required"] = "non-empty-param"
printRequiredParam(params) // prints "non-empty-param"
printRequiredParamByUpperCase(params) // prints "NON-EMPTY-PARAM"
//sampleEnd
}
© 2010–2021 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/require-not-null.html