You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin空安全与非空操作:intent.extras为null时条件语句的行为

条件语句在intent.extras为null时的执行行为

当intent.extras为null时,这段条件语句的执行逻辑如下:

if (intent.extras?.getBoolean(AppConstants.KEY_IS_FROM_NOTIFICATION) == true)

  1. 安全调用操作符的作用:?.是Kotlin的安全调用操作符,当调用者(这里是intent.extras)为null时,会直接返回null,不会执行后面的getBoolean方法,避免触发空指针异常。
  2. 与true的比较:此时表达式intent.extras?.getBoolean(...)的结果是null,而null == true的判断结果为false。
  3. 分支走向:因为整个if条件的结果是false,程序会进入else分支,执行finish()方法,结束当前Activity。

对应的完整代码参考:

if (intent.extras?.getBoolean(AppConstants.KEY_IS_FROM_NOTIFICATION) == true) {
    val intent = Intent(
        this, SplashScreen::class.java
    ).apply {
        addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }
    startActivity(intent)
} else {
    finish()
}

内容的提问来源于stack exchange,提问作者Amit Yadav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 07:07:04