Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private String properties are nullable in decompiled .java class Kotlin

When I have a private String property in a Kotlin class and decompile the class into Java code, this property won't have the @NotNull annotation. In contrast if I declare a "public" String property, it will have the annotation @NotNull in the decompiled code.

Here an .kt example:

   class Boo {

      private var  myString : String = ""
      var myOtherString : String = ""

   }

and the decompiled .java equivalent:

public final class Boo {
   private String myString = "";
   @NotNull
   private String myOtherString = "";

   @NotNull
   public final String getMyOtherString() {
      return this.myOtherString;
   }

   public final void setMyOtherString(@NotNull String var1) {
      Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
      this.myOtherString = var1;
   }

}

Why is it that @NotNull is not needed for private String properties?

like image 603
Shorxy Avatar asked Sep 14 '25 18:09

Shorxy


1 Answers

Think the other way around: what is the benefit of providing @NotNull on the public property (and not e.g. hiding all the information in @Metadata)? It doesn't have any meaning to the JVM runtime; the main benefit is as documentation for the users of the class and their tools, so they know getMyOtherString never returns null. But they can't access myString in the first place, so there's no point annotating it.

This doesn't quite answer why the field myOtherString is annotated and not just the getter and setter; I would guess that's because it can be exposed with @JvmField, so writing code which annotates it in some circumstances is necessary and it was slightly more convenient to not check whether the field is visible.

like image 190
Alexey Romanov Avatar answered Sep 17 '25 08:09

Alexey Romanov