checkNotNull

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

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

Since Kotlin

1.1

Samples

import kotlin.test.*

fun main() { 
   //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
}

inline fun <T : Any> checkNotNull(value: T?, lazyMessage: () -> Any): T(source)

Throws an IllegalStateException with the result of calling lazyMessage if the value is null. Otherwise returns the not null value.

Since Kotlin

1.1

Samples

import kotlin.test.*

fun main() { 
   //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
}
inline fun <T : Any> checkNotNull(value: T?): T(source)

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

Since Kotlin

1.0

Samples

import kotlin.test.*

fun main() { 
   //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
}

inline fun <T : Any> checkNotNull(value: T?, lazyMessage: () -> Any): T(source)

Throws an IllegalStateException with the result of calling lazyMessage if the value is null. Otherwise returns the not null value.

Since Kotlin

1.0

Samples

import kotlin.test.*

fun main() { 
   //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
}