LinkedIn Question
What can const val do which @JvmField val cannot?
There are multiple answers about difference between Val and const.
What is the difference between canst Val and @JvmField Val?
LinkedIn Question
What can const val do which @JvmField val cannot?
There are multiple answers about difference between Val and const.
What is the difference between canst Val and @JvmField Val?
I'm not sure how the confusion arose, but these 2 concepts are not really related. const val is about declaring compile-time constants, while @JvmField is about exposing a property as a field instead of through getters/setters.
What can
const valdo which @JvmField val cannot?
1 - const val makes the compiler inline the value of the constant in all usage sites. Usages of the constant are not even visible in the bytecode, just the constant's value is present.
This has an important consequence: if module A uses a const val declared in module B, and the value of the constant is later changed in module B, then module A needs to be recompiled against the new version of module B to see the change. Otherwise, A would still use the old constant value, even if the new module B is on the classpath.
2 - const val is a platform-independent concept, it can be used on JS or Native platforms as well, not only on JVM. @JvmField is a JVM concept.
Other differences of note:
const val can only be used at the top-level or in objects, while @JvmField can be used on any property.const val can only contain values of primitive types or String, and the initializer expression must be simple enough to be evaluated at compile time.Just for reference, the @JvmField annotation is used on Kotlin properties to expose them as fields instead of the usual getter/setter convention of properties.
The following Kotlin code:
class A {
val prop: Int = 42
}
Is compiled to bytecode that's equivalent to this Java code:
public final class A {
private final int prop = 42;
public int getProp() {
return this.prop;
}
}
While with the @JvmField annotation, the field would be directly exposed publicly without getter:
public final class A {
public final int prop = 42;
}
Unlike with const val, the compiler does not inline the value of a @JvmField-annotated property. The property doesn't even have to be a val - you could have a @JvmField-annotated var property, which is definitely not a constant.