Question about null checking on each access to lateinit var

Hello, Everyone,

I have a question about null checking before access to lateinit var in bytecode.

Let’s say we have this class:

class Test {
  lateinit var t: String

  init {
    t = "123"
  }

  fun test() {
      println(t)
      println(t)
  }
}

fun main() {
   val o = Test()
   o.test()
}

Now if we look in decompiled Java bytecode we see this code for method test:

public final void test() {
  String var10000 = this.t;
  if (this.t == null) {
     Intrinsics.throwUninitializedPropertyAccessException("t");
  }

  String var1 = var10000;
  System.out.println(var1);
  var10000 = this.t;
  if (this.t == null) {
     Intrinsics.throwUninitializedPropertyAccessException("t");
  }

  var1 = var10000;
  System.out.println(var1);

}

I’m interested why we have two null checks for variable t. We have already checked it for null on the first access, why we need the second check?

Nothing bad with the second check for me. But Findbug displays false positive error on the second null check with the text:

RCN: Nullcheck of value previously dereferenced 
(RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE)

A value is checked here to see whether it is null, but this value can't be null because it was 
previously dereferenced and if it were null a null pointer exception would have occurred at the earlier 
dereference. Essentially, this code and the previous dereference disagree as to whether this value is 
allowed to be null. Either the check is redundant or the previous dereference is erroneous.

Thank you for answers.

Thanks, I added a comment about FindBugs to this issue: https://youtrack.jetbrains.com/issue/KT-28331

1 Like

Thank you Alexey,
We have already suppressed this error, but it’s good that there is a ticket for this.