Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Difference between the behavior of const and @JvmField #328

Open
ythy opened this issue Jul 21, 2020 · 0 comments
Open

Difference between the behavior of const and @JvmField #328

ythy opened this issue Jul 21, 2020 · 0 comments
Labels

Comments

@ythy
Copy link
Owner

ythy commented Jul 21, 2020

  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.

@ythy ythy added the Kotlin label Jul 21, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant