Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Kotlin null-safe behavior

Tags:

kotlin

If global property is defined as private var raceLoadJob: Job? = null then Kotlin will ask you to do something like this in your method

if (raceLoadJob != null){
    if (raceLoadJob!!.isActive) return // null assertation
}

Kotlin will ask for assertation, because raceLoadJob value can be changed. The first thing I thought about is multi-threading.

So you can change code to

raceLoadJob?.let {
    if (it.isActive) return
}

But if you decompile this part of code you will see

Job var10000 = this.raceLoadJob;
if (this.raceLoadJob != null) {
   Job var1 = var10000;
   if (var1.isActive()) {
      return;
   }
}

You can see, that condition is this.raceLoadJob != null, but not var10000 != null. It means that in theory this code can fail because of raceLoadJob value is assigned, but var10000 is null.

Is this an issue or I have an error in my reasoning?

like image 576
Ufkoku Avatar asked Oct 18 '25 01:10

Ufkoku


1 Answers

The error in your reasoning is that you're analyzing the behavior of Kotlin code by looking at the decompiler output and not at the bytecode. The Kotlin compiler generates patterns of bytecode which are not used by javac, so the decompiler (which was designed to decompile javac output) can only provide an approximate representation of the actual logic.

If you look at the actual bytecode, it looks like this:

ALOAD 0
GETFIELD raceLoadJob : LRaceLoadJob;
DUP
IFNULL L1
ASTORE 2

It shows that the value being checked for null is exactly the same that is being used in subsequent computations.

like image 154
yole Avatar answered Oct 20 '25 23:10

yole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!