What is the Kotlin double-bang (!!) operator?

后端 未结 3 1345
天涯浪人
天涯浪人 2020-12-02 08:28

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?

3条回答
  •  一整个雨季
    2020-12-02 08:36

    Double-bang operator is an excellent option for fans 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.

    val nonNull = a!!.length
    

    So you can write a!!, and this will return a non-null value of a (a String here for example) or throw an NPE if a 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.

提交回复
热议问题