How do I force unwrap a nullable value with !! in Kotlin (and why should I avoid it)?

In Kotlin, !! is the not-null assertion operator. It forcefully converts a nullable value like String? into a non-null value like String.

val name: String? = getName()

val length = name!!.length

This tells Kotlin:

“Trust me, name is not null.”

If name is actually null at runtime, Kotlin throws a NullPointerException.

val name: String? = null

println(name!!.length) // Throws NullPointerException

Why you should avoid !!

You should avoid !! because it bypasses Kotlin’s null-safety system. Kotlin’s nullable types exist specifically to help prevent null-related crashes, and !! effectively says: “ignore that safety check.”

Problems with !!:

  • It can cause runtime crashes.
  • It hides the fact that a value may be missing.
  • It often makes code less clear and less robust.
  • It usually means null handling should be improved.

Prefer safer alternatives

Use a safe call

val length = name?.length

If name is null, length becomes null.

Use Elvis operator for a default value

val length = name?.length ?: 0

If name is null, length becomes 0.

Use an explicit null check

if (name != null) {
    println(name.length)
} else {
    println("Name is missing")
}

Inside the if, Kotlin smart-casts name to a non-null String.

Use let

name?.let {
    println(it.length)
}

This only runs the block when name is not null.

Fail deliberately with a clearer message

If null truly represents a programmer error, prefer requireNotNull, checkNotNull, or an explicit error message:

val length = requireNotNull(name) { "Name must not be null" }.length

This still fails fast, but the error is much clearer than a generic NullPointerException.

When is !! acceptable?

Use !! only when you are absolutely certain the value cannot be null, and if it is null, that indicates a serious programming error.

Even then, this is usually better:

val user = requireNotNull(findUser(id)) {
    "Expected user with id=$id to exist"
}

Rule of thumb

If you are tempted to write this:

value!!

First ask whether one of these would be better:

value?.someCall()
value ?: defaultValue
if (value != null) { /* use value */ }
requireNotNull(value) { "Helpful error message" }

In most Kotlin code, !! should be rare.

How do I throw an exception when a value is null using ?: throw in Kotlin?

Use Kotlin’s Elvis operator ?: with throw on the right-hand side:

val value: String? = getNullableValue()

val nonNullValue: String = value ?: throw IllegalArgumentException("value must not be null")

Because throw is an expression in Kotlin, it can be used after ?:.

Example

fun printLength(text: String?) {
    val nonNullText = text ?: throw IllegalArgumentException("text must not be null")

    println(nonNullText.length)
}

If text is not null, it is assigned to nonNullText as a non-nullable String.
If text is null, the exception is thrown.

You can also use other exception types:

val id = nullableId ?: throw IllegalStateException("ID was unexpectedly null")

A common choice is:

  • IllegalArgumentException when a function argument is invalid
  • IllegalStateException when the object/program state is invalid

How do I use the Elvis operator to provide default values in Kotlin?

In Kotlin, the Elvis operator ?: provides a fallback value when the expression on its left is null.

val result = nullableValue ?: defaultValue

If nullableValue is not null, result gets that value.
If nullableValue is null, result gets defaultValue.

Example:

val name: String? = null

val displayName = name ?: "Guest"

println(displayName) // Guest

With a non-null value:

val name: String? = "Alice"

val displayName = name ?: "Guest"

println(displayName) // Alice

It’s often used with safe calls:

val name: String? = null

val nameLength = name?.length ?: 0

println(nameLength) // 0

Here, name?.length returns null if name is null, so ?: 0 supplies the default.

You can also use it with functions:

fun getUsername(): String? {
    return null
}

val username = getUsername() ?: "anonymous"

And because throw and return are expressions in Kotlin, they can be used on the right side:

fun printName(name: String?) {
    val actualName = name ?: return
    println(actualName)
}
fun requireName(name: String?) {
    val actualName = name ?: throw IllegalArgumentException("Name is required")
    println(actualName)
}

So the basic pattern is:

val value = somethingNullable ?: fallbackValue

How do I use the safe call operator `?.` in Kotlin?

In Kotlin, the safe call operator ?. lets you access a property or call a function only if the value is not null.

If the value is null, the expression simply returns null instead of throwing a NullPointerException.

val name: String? = null

val length = name?.length

println(length) // null

Here, name is nullable because its type is String?. Since name is null, name?.length does not try to access .length; it returns null.

Basic syntax

nullableValue?.property
nullableValue?.function()

Example:

val user: User? = getUser()

val email = user?.email

If user is not null, email gets user.email.

If user is null, email becomes null.

Chaining safe calls

You can chain multiple safe calls together:

val city = user?.address?.city

This means:

  • if user is null, return null
  • otherwise check address
  • if address is null, return null
  • otherwise return city

Using ?. with a default value

Often, you combine ?. with the Elvis operator ?::

val length = name?.length ?: 0

This means:

  • if name is not null, use name.length
  • if name is null, use 0

Using ?.let

Use ?.let when you want to run code only when a value is not null:

val name: String? = "Kotlin"

name?.let {
    println("Name is $it")
    println("Length is ${it.length}")
}

The block runs only if name is not null.

Safe call on assignment

Safe calls can also be used on the left side of an assignment:

person?.address?.city = "Paris"

If person or address is null, the assignment is skipped.

Summary

val result = nullableValue?.someProperty

Use ?. when:

  • a value might be null
  • you want to avoid NullPointerException
  • returning null is acceptable when the receiver is null

Common pattern:

val result = nullableValue?.someProperty ?: defaultValue

How do I declare nullable variables using `?` in Kotlin?

In Kotlin, you declare a nullable variable by adding ? after the type.

var name: String? = null

This means name can hold either a String value or null.

Examples:

var age: Int? = null
age = 25

val email: String? = "[email protected]"
val phone: String? = null

Without ?, Kotlin does not allow null:

var name: String = null // Error

With ?, you must handle possible null safely:

val name: String? = null

println(name?.length) // Safe call, prints null instead of crashing

You can also provide a default value with the Elvis operator ?::

val name: String? = null
val length = name?.length ?: 0

println(length) // 0

So the basic pattern is:

var variableName: Type? = null