kotlin - Kotlin - How does Boolean? in if expression works on bytecode
问题描述
I know the idiom for consuming nullable Booleans in Kotlin is:
fun nullableBoolean(b: Boolean?) {
if (b == true) {
println("is true")
}
}
I'm curious about what happens under the hood. This is the interesting part of the generated bytecode for this function:
public final static nullableBoolean(Ljava/lang/Boolean;)V
@Lorg/jetbrains/annotations/Nullable;() // invisible, parameter 0
L0
LINENUMBER 4 L0
ALOAD 0
ICONST_1
INVOKESTATIC java/lang/Boolean.valueOf (Z)Ljava/lang/Boolean;
INVOKESTATIC kotlin/jvm/internal/Intrinsics.areEqual (Ljava/lang/Object;Ljava/lang/Object;)Z
IFEQ L1
...
I can see that Intrinsics.areEqual
does a null check. But I don't understand what happens with the call to java/lang/Boolean.valueOf
when the reference is null
解决方案
Boolean.valueOf
正在调用常量true
以创建一个装箱的布尔对象。然后将其与传递给函数的值进行比较。
推荐阅读
- google-sheets - 基于 18 个月前的日期的条件格式
- firebase - Firebase Environmental Config - Added slashes to private_key_id
- javascript - 如何使用 React Ref 调用 video.play()?
- android - 颤振重新定位键盘向下
- javascript - 标题出现在滚动条上?
- prolog - Prolog returning only the max value from all iterations
- python - How large can a TensorFlow .record file be before it causes performance issues?
- google-chrome-extension - Chrome Extension Unchecked runtime.lastError while running events.addRules:主机值需要小写
- go - 如何动态调用变量?
- r - 是否可以安排 R 脚本在 R 中的机器映像 (EC2) 上运行?