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

后端 未结 3 1344
天涯浪人
天涯浪人 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:47

    Here is an example to make things clearer. Say you have this function

    fun main(args: Array) {
        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) {
        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) {
        var email: String?
        email = null
        println(email!!)
    }
    

    This will throw a KotlinNullPointerException

提交回复
热议问题