You can use Kotlin bytecode viewer to find out what these options are compiled to.
With Kotlin 1.0.2 the compiled bytecode shows that
object
或companion object
中的val
属性被编译为类内的private static final
字段:
// access flags 0x1A
private final static I FILES_TO_DOWNLOAD = 100
还有一个getter,在引用属性时称为:
// access flags 0x1019
public final static synthetic access$getFILES_TO_DOWNLOAD$cp()I
在Java中,getter可以分别称为DefaultValues.INSTANCE.getFILES_TO_DOWNLOAD()
或DefaultValues.Companion.getFILES_TO_DOWNLOAD()
.
Non-const
top level property is compiled to the same to (1) with only difference that the field and getter are placed inside FilenameKt
class now.
但是顶级const val
被编译成public static final
字段:
// access flags 0x19
public final static I DEFAULT_FILES_TO_DOWNLOAD = 100
The same public static final field will be produced when a const val
is declared inside an object. Also, you can achieve the same resulting bytecode if you add @JvmField
annotation to the properties declared in (1).
Concluding that, you can define public static final
field using const
or @JvmField
either in an object
or at top level.