Why does Kotlin need "const" keyword?

Sorry, I can’t quite get this phrase.

Here’s the source:

val foo1 = 42
const val foo2 = 43

object Bar {
  val bar1 = "bar1"
  const val bar2 = "bar2"
}

fun main(args: Array<String>) {
  println(foo1)
  println(foo2)
  println(Bar.bar1)
  println(Bar.bar2)
}

And here’s what javap -p shows:

Compiled from "Foo.kt"
public final class FooKt {
  private static final int foo1;
  public static final int foo2;
  public static final int getFoo1();
  public static final void main(java.lang.String[]);
  static {};
}
Compiled from "Foo.kt"
public final class Bar {
  private static final java.lang.String bar1;
  public static final java.lang.String bar2;
  public static final Bar INSTANCE;
  public final java.lang.String getBar1();
  private Bar();
  static {};
}

As you can see, the difference is only whether the field will be private or public. I can’t see how that impedes interop nor reflection.

1 Like