What is the double exclamation before the method call in Kotlin?

14

I'm studying Kotlin. I noticed that, in the conversion to type int , it is necessary to put the double exclamation ( !! ).

Example:

var input = readLine()!!.toInt();

Generally in other languages double exclamation is used to cast a value to boolean . But in this case, it does not seem to be cast, since it is not a Boolean operation (as is the case with condition checking).

So, what is the use of this double exclamation, which is before toInt , in Kotlin?

    
asked by anonymous 05.08.2017 / 22:02

1 answer

11

Kotlin hates null reference error, one of the biggest criticisms of Java. So by default it is not possible to create code that tries to access a null. But you might want this, probably to be compatible with some Java code, or maybe because you're missing a screw :) That's where this operator comes in. It tries to access the value of the variable, but if it is null it throws a NullPointerException as Java would. That is, you are telling the compiler to ignore what it normally does to prohibit access at null value and leave the decision to do at runtime .

fun main(args: Array<String>) {
    val texto: String? = null
    println(texto!!) //gerará uma exceção
    //seria o mesmo que println(texto ?: throw NullPointerException())
    //ou ainda println(texto != null ? texto : throw NullPointerException())
}

See running ideone . And at Coding Ground . Also I placed GitHub for future reference .

If you take out !! the code does not compile, which is usually the best thing to do anyway.

    
05.08.2017 / 23:26