What is the Kotlin double-bang (!!) operator?
!!(Double Bang) operator is an operator to assert forcibly nullable variable as not null.
Example: Here str is a string with value. But its nullable. Since its nullable we need to handle null for avoid compile time exceptions.
val str :String? = "Foo"
val lowerCase = str!!.lowerCase()
Here if we add !! operator, since it has non null value it would work and lowercased value will be assigned.
val str :String? = "Foo"
str = null
val lowerCase = str!!.lowerCase()
But here if you assign null value and use the particular value , it will throw KotlinNullPointerException.
One important thing here is, in most of the cases one should avoid as !! operator unless if its 100% sure that value is non null value or if the exception is caught and handled properly.
If you need to avoid this NPE, you can use null safe operators with elvis operators. null safe call ?. opertators with elvis are better way to handle null safety in kotlin. You can read more about Kotlin null safety here
Kotlin's double-bang operator is an excellent sample for fans of NullPointerException
(NPE).
The not-null assertion operator
!!
converts any value to a non-null type and throws an exception if the value is null.
val nonNull = str!!.length
If you write str!!
, it'll return a non-null value of str
(str
is a String?
here) or throw an NPE if str
is null. This operator should be used in cases where the developer is guaranteeing – the value will never be null. If you want an NPE, you have to ask for it explicitly.
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