Skip to content

Difference between the behavior of const and @JvmField #328

@ythy

Description

@ythy
  1. const it only works with primitives and Strings:
class Constants {
  companion object {
    // won't compile
    const val FOO = Foo()
  }
}
  1. accesses to a const val get inlined by the compiler, while @JvmFields don't
class Constants {
  companion object {
    @JvmField val FOO = Foo()
  }
}

Let's take the following code:

fun main(args: Array<String>) {
  println(Constants.FOO)
}

Here's what we get with @JvmField val FOO = Foo():

public final class MainKt {
   public static final void main(@NotNull String[] args) {
      Intrinsics.checkParameterIsNotNull(args, "args");
      Foo var1 = Constants.FOO;
      System.out.println(var1);
   }
}

And with const val FOO = "foo":

public final class MainKt {
   public static final void main(@NotNull String[] args) {
      Intrinsics.checkParameterIsNotNull(args, "args");
      String var1 = "foo";
      System.out.println(var1);
   }
}

There's no call to Constants.FOO in the second example, the value has been inlined.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions