What’s the point of double exclamation before the method call on Kotlin?

Asked

Viewed 920 times

14

I’m studying Kotlin. I realized that in converting to the type int, it is necessary to place the double exclamation (!!).

Example:

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

Generally in other languages, double exclamation is used to cast a value for boolean. However, in this case, it does not seem to be cast, since it is not a boolean operation (as is the case of checking conditions).

So, what’s the point of this double exclamation, which is before toInt, in Kotlin?

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 it may be that you want this, probably to be compatible with some Java code, or maybe because you lack a screw :) That’s where this operator comes in. It attempts to access the value of the variable, but if it is null launches a NullPointerException like Java would do. That is, you are telling the compiler to ignore what it normally does of prohibiting access in null value and leave the decision of what to do in running time.

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())
}

Behold "working" in the ideone. And in the repl it.. Also put on the Github for future reference.

If you take the !! the code neither compiles, which is usually the best to do even.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.