Menu
Coddy logo textTech

Not Null Assertion

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 17 of 93.

The safe call operator and Elvis operator handle nulls gracefully, but sometimes you're absolutely certain a nullable value isn't null at a specific point in your code. The not-null assertion operator !! lets you tell Kotlin: "I guarantee this isn't null."

fun main() {
    val name: String? = "Alice"
    val length = name!!.length  // Converts String? to String
    println(length)  // Prints: 5
}

The !! operator converts a nullable type to its non-nullable counterpart. However, if the value actually is null, your program will crash with a NullPointerException:

fun main() {
    val name: String? = null
    val length = name!!.length  // Crashes here!
}

When to use it: Only use !! when you have logic that guarantees the value cannot be null, but the compiler can't verify it. In most cases, prefer safe calls ?. or the Elvis operator ?: instead. The not-null assertion should be your last resort, not your first choice.

challenge icon

Challenge

Easy

Write a function getUppercaseLength that takes a text parameter and returns the length of its uppercase version.

The function receives a non-null string value, but the parameter type is nullable (String?). Use the not-null assertion operator !! to convert it to a non-nullable type, then chain the uppercase() method and get the length.

Parameters:

  • text (String?): A nullable string that is guaranteed to contain a value

Returns: The length of the uppercase version of the text (Int)

Note: For this challenge, the input will always be a valid string, never null. This simulates a scenario where you know the value exists but the compiler cannot verify it.

Try it yourself

fun getUppercaseLength(text: String?): Int {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground