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"))
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 a good option for lovers 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.So you can write
a!!
, and this will return a non-null value ofa
(aString
here for example) or throw an NPE ifa
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.
Hope this helps.
Here is an example to make things clearer. Say you have this function
This will produce the following compilation error.
Now you can prevent that by adding a question mark to the
String
type to make it nullable.So we have
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
This will throw a
KotlinNullPointerException
This is unsafe nullable type (
T?
) conversion to a non-nullable type (T
). It will throwNullPointerException
if the value isnull
.It is documented here along with Kotlin means of null-safety.