Kotlin - why do I get a KotlinNullPointerException

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

Consider the following code:

Example

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

fun maybeWriteMessage(message:         


        
4条回答
  •  爱一瞬间的悲伤
    2021-01-17 16:29

    message: String? is indicating that message may or may not be null.

    Since your function maybeWriteMessage has a default value of null for message and you are calling maybeWriteMessage() without specifying message - the default value (null) will be used when calling writeMessage(message!!).

    As written in the documentation the !!-operator throws an exception when the value is null.

    One way to trigger writeMessage safely would be to use .let:

    fun maybeWriteMessage(message: String? = null) {
        message?.let { 
          writeMessage(it)
        }
    }
    

提交回复
热议问题