What is the Kotlin double-bang (!!) operator?
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"))
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