Sobes.tech
Junior

What are two exclamation marks used for in programming?

sobes.tech AI

Answer from AI

The two exclamation marks !! in Kotlin are used for unsafe cast (type casting without checks).

// Example of unsafe cast
val value: Any? = "Hello"
val str: String = value as String // Regular cast, may throw ClassCastException
val anotherStr: String = value!! as String // Unsafe cast. If value is not String, it will also throw ClassCastException, but the !! syntax applies to nullability

The main purpose of !! is to convert a nullable type to a non-nullable type, explicitly stating that the developer is sure that the variable will not be null at this point in execution.

// Example of using !! to convert nullable to non-nullable
var name: String? = "Kotlin"
val length: Int = name!!.length // Explicitly stating that name is not null

If, during code execution, the variable to which !! is applied turns out to be null, a KotlinNullPointerException will be thrown.

This should be used cautiously, only when you are 100% sure there is no null. In most cases, it is preferable to use safer mechanisms such as:

  • Safe call operator: ?.
  • Elvis operator: ?:
  • Null check (if (variable != null))
  • Functions let, run, also, apply with null check
// Examples of safe null handling
var surname: String? = null
val lenSafeCall: Int? = surname?.length // Safe call operator, returns null if surname is null

val lenElvis: Int = surname?.length ?: 0 // Elvis operator, returns 0 if surname is null

if (surname != null) {
    val lenIf: Int = surname.length // Smart cast after null check
}

surname?.let {
    // Code executes only if surname is not null
    val lenLet: Int = it.length
}

Thus, !! is a tool for converting a nullable type to a non-nullable one, carrying the risk of NullPointerException and used for explicit assertion of non-nullity at the call site.