What is the Kotlin double-bang (!!) operator?

KotlinKotlin Null-Safety

Kotlin Problem Overview


I'm converting Java to Kotlin with Android Studio. I get double bang after the instance variable. What is the double bang and more importantly where is this documented?

mMap!!.addMarker(MarkerOptions().position(london).title("Marker in London"))
    

Kotlin Solutions


Solution 1 - Kotlin

This is unsafe nullable type (T?) conversion to a non-nullable type (T), !! will throw NullPointerException if the value is null.

It is documented here along with Kotlin means of null-safety.

Solution 2 - Kotlin

Here is an example to make things clearer. Say you have this function

fun main(args: Array<String>) {
    var email: String
    email = null
    println(email)
}

This will produce the following compilation error.

Null can not be a value of a non-null type String

Now you can prevent that by adding a question mark to the String type to make it nullable.

So we have

fun main(args: Array<String>) {
    var email: String?
    email = null
    println(email)
}

This produces a result of

null

Now if we want the function to throw an exception when the value of email is null, we can add two exclamations at the end of email. Like this

fun main(args: Array<String>) {
    var email: String?
    email = null
    println(email!!)
}

This will throw a KotlinNullPointerException

Solution 3 - Kotlin

Double-bang operator is an excellent option for fans of NullPointerException (or NPE for short).

>The not-null assertion operator !! converts any value to a non-null type and throws an exception if the value is null.

val nonNull = a!!.length

So you can write a!!, and this will return a non-null value of a (a String here for example) or throw an NPE if a is null.

If you want an NPE, you can have it, but you have to ask for it explicitly. This operator should be used in cases where the developer is guaranteeing – the value will never be null.

Solution 4 - Kotlin

!! is an assertion that it is not null. Two exclamation marks after a nullable value convert it to a non-nullable type. At the same time, before the conversion, it is not checked in any way that the value really does not contain null. Therefore, if during the execution of the program it turns out that the value that the !! operator is trying to convert is still null, then there will be only one way out - to throw a NullPointerException.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmbr_at_mlView Question on Stackoverflow
Solution 1 - KotlinhotkeyView Answer on Stackoverflow
Solution 2 - KotlinAlf MohView Answer on Stackoverflow
Solution 3 - KotlinAndy JazzView Answer on Stackoverflow
Solution 4 - KotlinVlad TkachevView Answer on Stackoverflow