What's the difference between !! and ? in Kotlin?
Solution 1:
As it said in Kotlin reference, !!
is an option for NPE-lovers :)
a!!.length
will return a non-null value of a.length
or throw a NullPointerException if a
is null
:
val a: String? = null
print(a!!.length) // >>> NPE: trying to get length of null
a?.length
returns a.length
if a
is not null
, and null
otherwise:
val a: String? = null
print(a?.length) // >>> null is printed in the console
To sum up:
+------------+--------------------+---------------------+----------------------+
| a: String? | a.length | a?.length | a!!.length |
+------------+--------------------+---------------------+----------------------+
| "cat" | Compile time error | 3 | 3 |
| null | Compile time error | null | NullPointerException |
+------------+--------------------+---------------------+----------------------+
Might be useful: What is a NullPointerException?
Solution 2:
the precedence of operators !
, ?.
, !!
is ?.
> !!
> !
.
the !!
operator will raising KotlinNullPointerException
when operates on a null
reference, for example:
null!!;// raise NullPointerException
the safe call ?.
operator will return null
when operates on a null
reference, for example:
(null as? String)?.length; // return null;
the !!
operator in your second approach maybe raise NullPointerException
if the left side is null
, for example:
mCurrentDataset?.load(..)!!
^-------------^
|
when mCurrentDataset== null || load() == null a NullPointerException raised.
you can using the elvis operator ?:
instead of the !!
operator in your case, for example:
!(mCurrentDataset?.load(..)?:false)