Search code examples
kotlinstatic-methods

Why is it possible for a JvmStatic method to access and modify state?


I would've assumed that a method annotated with @JvmStatic would be unable to access, let alone modify, a class property.

Based on the following this is not the case. This code clearly updates state, printing From main - 11.

object Foo {
    var bar = 5

    @JvmStatic
    fun updateBar(updateVal : Int) {
        println("bar = $bar")
        bar += updateVal
        println("bar = $bar")
    }
}

fun main() {
    Foo.updateBar(6)
    println("From main - ${Foo.bar}")
}

Solution

  • I was also surprised by this. In fact, because Foo is an object, the field bar is actually a static field on the JVM. That's why it's not a problem to access it from a static method.

    The decompiled Java code of your class is the following:

    public final class Foo {
       private static int bar;
       public static final Foo INSTANCE;
    
       public final int getBar() {
          return bar;
       }
    
       public final void setBar(int var1) {
          bar = var1;
       }
    
       @JvmStatic
       public static final void updateBar(int updateVal) {
          String var1 = "bar = " + bar;
          boolean var2 = false;
          System.out.println(var1);
          bar += updateVal;
          var1 = "bar = " + bar;
          var2 = false;
          System.out.println(var1);
       }
    
       private Foo() {
       }
    
       static {
          Foo var0 = new Foo();
          INSTANCE = var0;
          bar = 5;
       }
    }
    
    

    However, I would avoid doing this. It's unexpected and doesn't really convey the intent.