kotlin.checkNotNull

checkNotNull

inline fun <T : Any> checkNotNull(value: T?): T

Throws an IllegalStateException if the value is null. Otherwise returns the not null value.

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
}

assertFailsWith<IllegalStateException> {
    getStateValue()
}

assertFailsWith<IllegalStateException> {
    someState = ""
    getStateValue()
}.let { exception ->
    println(exception.message) // State must be non-empty
}
//sampleEnd
}
inline fun <T : Any> checkNotNull(
    value: T?, 
    lazyMessage: () -> Any
): T

Throws an IllegalStateException 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
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
}

assertFailsWith<IllegalStateException> {
    getStateValue()
}

assertFailsWith<IllegalStateException> {
    someState = ""
    getStateValue()
}.let { exception ->
    println(exception.message) // State must be non-empty
}
//sampleEnd
}

© 2010–2017 JetBrains s.r.o.
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/check-not-null.html

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部