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

冷暖自知 提交于 2019-11-27 19:12:27
hotkey

This is unsafe nullable type (T?) conversion to a non-nullable type (T). It will throw NullPointerException if the value is null.

It is documented here along with Kotlin means of null-safety.

Alf Moh

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

This is a good option for lovers 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 lll = 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.

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!