kotlin允许方法传null值时遇到的问题

来源:互联网 发布:青岛知豆租赁电话 编辑:程序博客网 时间:2024/05/21 19:45

kotlin allow method params specified as null

问题描述:

定义了一个允许设null值的Long型变量

private var categoryId: Long? = null

定义允许传null值参数categoryId的方法

interface OnConfirmClick {    fun onClick(categoryId: Long?, tagIdList: MutableList<Long>?, crowdIdList: MutableList<Int>?)}

调用方法时传入定义的categoryId变量

skuConfirmTv.setOnClickListener {    if (onConfirmClickListener != null) {        onConfirmClickListener?.onClick(categoryId!!, tagIdList, crowdIdList)    }}

按照习惯,一般使用了可能为null的变量categoryId应当在后面加!!,但是运行后竟然报错KotlinNullPointerException

报的错误如下:

Process: com.newcare.hes, PID: 19664kotlin.KotlinNullPointerException  at com.newcare.hes.control.sku.SkuScreenView$init$2.onClick(SkuScreenView.kt:66)  at android.view.View.performClick(View.java:6256)  at android.view.View$PerformClick.run(View.java:24697)  at android.os.Handler.handleCallback(Handler.java:789)  at android.os.Handler.dispatchMessage(Handler.java:98)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6541)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)         

解决方法:

经过一番努力找到原因了,调用方法时应当去掉!!,具体原理是什么有待分析。。。

skuConfirmTv.setOnClickListener {    if (onConfirmClickListener != null) {        onConfirmClickListener?.onClick(categoryId, tagIdList, crowdIdList)    }}
原创粉丝点击