首页 > 解决方案 > 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

标签: kotlinbytecode

解决方案


Boolean.valueOf正在调用常量true以创建一个装箱的布尔对象。然后将其与传递给函数的值进行比较。


推荐阅读