自动化零件商城(www.rssme.com)专业PLC,变频器,直线模组,触摸屏,控制器,传感器等自动化商品网上购物商城,为广大中小工业企业提供优质、低价格和种类齐全的自动化零件。
文章目录

前言

简单记录一下Kotlin中?.和!!之间的区别,记录于此,方便自己查阅和回顾。

‌Kotlin中的?.和!!主要区别在于它们对空指针的处理方式

正文

?.

不会抛出空指针异常,而是安全地处理null值‌

‌?.为安全调用操作符

  1. 当变量不为null时,使用?.可以安全地调用其方法或属性

  2. 当变量为null,则不执行调用,直接返回null

val biuMall: String? = null
Log.d(TAG, "biuMall length : "+ biuMall?.length)

biuMall为null,因此上面打印为

biuMall length : null

!!

如果变量为null,则抛出异常‌

‌!!为非空断言操作符

  1. 当变量不为null时,使用!!会强制执行调用

  2. 当变量为null,则会抛出空指针异常

val biuMall: String? = null
Log.d(TAG, "biuMall length : "+ biuMall!!.length)

biuMall为null,直接抛出异常

AndroidRuntime(13345): java.lang.RuntimeException: Unable to resume activity {com.biumall.demo/com.biumall.demo.MainActivity}: java.lang.NullPointerException
AndroidRuntime(13345):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4907)
AndroidRuntime(13345):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4940)
AndroidRuntime(13345):     at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:54)
AndroidRuntime(13345):     at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
AndroidRuntime(13345):     at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:178)
AndroidRuntime(13345):     at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:99)
AndroidRuntime(13345):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2393)
AndroidRuntime(13345):     at android.os.Handler.dispatchMessage(Handler.java:106)
AndroidRuntime(13345):     at android.os.Looper.loopOnce(Looper.java:201)
AndroidRuntime(13345):     at android.os.Looper.loop(Looper.java:288)
AndroidRuntime(13345):     at android.app.ActivityThread.main(ActivityThread.java:8061)
AndroidRuntime(13345):     at java.lang.reflect.Method.invoke(Native Method)
AndroidRuntime(13345):     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:703)
AndroidRuntime(13345):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:911)
AndroidRuntime(13345): Caused by: java.lang.NullPointerException
AndroidRuntime(13345):     at com.biumall.demo.MainActivity.onResume(MainActivity.kt:28)

参考文章

  1. Kotlin中的?.和!!主要区别

相关文章

自动化零件商城(www.rssme.com)专业PLC,变频器,直线模组,触摸屏,控制器,传感器等自动化商品网上购物商城,为广大中小工业企业提供优质、低价格和种类齐全的自动化零件。

暂无评论

评论审核已启用。您的评论可能需要一段时间后才能被显示。

none
暂无评论...