What's the difference between !! and ? in Kotlin?

后端 未结 6 1314
情深已故
情深已故 2020-12-04 14:15

I am new to Kotlin. I want to know the difference between this two !! and ? in below code.

Below, there are two snippets: the first uses

6条回答
  •  天涯浪人
    2020-12-04 14:56

    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)
    

提交回复
热议问题