Kotlin checkNotNull()

Kotlin checkNotNull()

The Kotlin checkNotNull() function is used to ensure that a given value is not null. If the value is null, it throws a IllegalStateException.

Syntax

The syntax of Kotlin checkNotNull() function is

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

where

ParameterDescription
valueThe value to be checked for null.
Parameters of checkNotNull() function

If the given value is null, the checkNotNull() function throws a IllegalStateException.

Examples

1. checkNotNull() with non-null argument

In this example, we’ll use checkNotNull() to ensure that a String value is not null.

Kotlin Program

fun main() {
    checkNotNull("Hello, Kotlin!")
    print("Given string is not null")
}

Output

Given string is not null

Since the given value to checkNotNull() is not a null value, but a valid string value, the checkNotNull() function did not raise an Exception.

2. checkNotNull() with null argument

Now, let us pass a null to checkNotNull() function, and observe the output.

Kotlin Program

fun main() {
    checkNotNull(null)
    print("Given string is not null")
}

Output

Exception in thread "main" java.lang.IllegalStateException: Required value was null.
	at MainKt.main(Main.kt:2)
	at MainKt.main(Main.kt)

Summary

In this tutorial, we’ve covered the Kotlin checkNotNull() function, its syntax, and how to use it to ensure non-null values during runtime. This function is helpful for catching potential null values early in the program’s execution.