Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What :: means in Kotlin?

:: converts a Kotlin function into a lambda. this translates to MyClass(x, y) in Kotlin.

What does Kotlin exclamation mark mean?

The type names or class names ending with single exclamation mark ! are called platform types in Kotlin. You find them when you are working in Kotlin with old Java code that doesn't contain nullability information.

What does the operator do in Kotlin?

Kotlin has a set of operators to perform arithmetic, assignment, comparison operators and more. You will learn to use these operators in this article. Operators are special symbols (characters) that carry out operations on operands (variables and values).

What is the Elvis operator in Kotlin?

Elvis Operator (?:)It is used to return the not null value even the conditional expression is null. It is also used to check the null safety of values. In some cases, we can declare a variable which can hold a null reference.


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.


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


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.