Kotlin - why do I get a KotlinNullPointerException

后端 未结 4 1774
借酒劲吻你
借酒劲吻你 2021-01-17 15:50

Consider the following code:

Example

fun main(args: Array) {
    maybeWriteMessage()
}

fun maybeWriteMessage(message:         


        
4条回答
  •  滥情空心
    2021-01-17 16:27

    From the documentation:

    The !! Operator

    The third option is for NPE-lovers: the not-null assertion operator (!!) converts any value to a non-null type and throws an exception if the value is null. We can write b!!, and this will return a non-null value of b (e.g., a String in our example) or throw an NPE if b is null:

    val l = b!!.length

    Thus, if you want an NPE, you can have it, but you have to ask for it explicitly, and it does not appear out of the blue.

    So regardless of whether your function uses the parameter or not, by using message!!, you are explicitly asking for a NPE.

提交回复
热议问题