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

后端 未结 6 1307
情深已故
情深已故 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:33

    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?

提交回复
热议问题