!! Non-Null Assertion
The !! operator (non-null assertion operator) in Kotlin treats a nullable value as a non-null type. If the value is null, a KotlinNullPointerException is thrown.
Syntax
// Use !! to convert a Nullable type to a non-null type. val name: String? = "Alice" val length: Int = name!!.length // Treated as String? → String. // If the value is null, KotlinNullPointerException is thrown. val nullValue: String? = null val len = nullValue!!.length // Exception thrown
Syntax List
| Syntax | Description |
|---|---|
| value!! | Returns the value as a non-null type if it is not null. Throws KotlinNullPointerException if null. |
| value!!.method() | Calls a method without a null check. Throws an exception if the value is null. |
| value!!.property | Accesses a property without a null check. |
Sample Code
// Demo of the !! operator
fun getUser(id: Int): String? = if (id > 0) "User-$id" else null
fun main() {
// Works normally when the value is not null.
val name: String? = "Alice"
println(name!!.length) // 5
println(name!!.uppercase()) // ALICE
// Example of using !! on the result of a function where smart cast is not available
val user = getUser(1)!! // When you know the result is not null
println("User: $user") // User: User-1
// Comparison with safer alternatives to !!
val nullable: String? = "Kotlin"
// Option 1: !! (throws if null)
println(nullable!!.length) // 6
// Option 2: ?.let (safe)
nullable?.let { println(it.length) } // 6
// Option 3: ?: (fallback value if null)
println(nullable?.length ?: 0) // 6
// Using !! on a null value causes an exception.
try {
val nullStr: String? = null
println(nullStr!!.length) // Exception thrown here
} catch (e: NullPointerException) {
println("Exception caught: ${e::class.simpleName}") // KotlinNullPointerException
}
}
Notes
The !! operator bypasses Kotlin's null safety features, so its use should be kept to a minimum. Overusing it in production code can lead to the same kinds of issues as Java's NullPointerException.
Warning: Using !! anywhere other than places where you are certain the value cannot be null is dangerous. Consider using the ?. operator, the ?: Elvis operator, or smart casting with ?.let instead.
For the basics of nullable types, see Nullable Types / ?. Operator. For setting default values, see ?: Elvis Operator.
If you find any errors or copyright issues, please contact us.