checkNotNull
Требования к платформе и версии: JVM (1.0), JS (1.0), Native (1.0)
fun <T : Any> checkNotNull(value: T?): T
Выбрасывает IllegalStateException, если значение value равно null. В противном случае возвращает ненулевое значение.
import kotlin.test.*
fun main(args: Array<String>) {
//sampleStart
var someState: String? = null
fun getStateValue(): String {
val state = checkNotNull(someState) { "State must be set beforehand" }
check(state.isNotEmpty()) { "State must be non-empty" }
// ...
return state
}
// getStateValue() // will fail with IllegalStateException
someState = ""
// getStateValue() // will fail with IllegalStateException
someState = "non-empty-state"
println(getStateValue()) // non-empty-state
//sampleEnd
}
Требования к платформе и версии: JVM (1.0), JS (1.0), Native (1.0)
inline fun <T : Any> checkNotNull( value: T?, lazyMessage: () -> Any ): T
Выбрасывает IllegalStateException с результатом вызова lazyMessage, если значение value равно null. В противном случае возвращает ненулевое значение.
import kotlin.test.*
fun main(args: Array<String>) {
//sampleStart
var someState: String? = null
fun getStateValue(): String {
val state = checkNotNull(someState) { "State must be set beforehand" }
check(state.isNotEmpty()) { "State must be non-empty" }
// ...
return state
}
// getStateValue() // will fail with IllegalStateException
someState = ""
// getStateValue() // will fail with IllegalStateException
someState = "non-empty-state"
println(getStateValue()) // non-empty-state
//sampleEnd
}
© 2010–2022 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/check-not-null.html