Kotlin中的静态数据 [英] Static data in Kotlin
问题描述
请告诉我,这个示例在Java方面有什么区别
Please tell me, is there any difference (in terms of Java) in this examples:
object DefaultValues {
val FILES_TO_DOWNLOAD = 100
}
和
class DefaultValues {
companion object {
val FILES_TO_DOWNLOAD = 100
}
}
没有类或对象包装器:
Without class or object wrapper:
const val DEFAULT_FILES_TO_DOWNLOAD = 100
和
val DEFAULT_FILES_TO_DOWNLOAD = 100
真正的定义方式是什么?:
What is the true way to define?:
public static final int FILES_TO_DOWNLOAD = 100
推荐答案
您可以使用 Kotlin字节码查看器找出这些选项被编译成什么.
You can use Kotlin bytecode viewer to find out what these options are compiled to.
使用Kotlin 1.0.2时,编译后的字节码显示
With Kotlin 1.0.2 the compiled bytecode shows that
-
val
属性被编译为类内的private static final
字段:
object
或companion object
中的val
property inobject
orcompanion object
is compiled into aprivate static final
field inside the class:
// access flags 0x1A
private final static I FILES_TO_DOWNLOAD = 100
和一个吸气剂,当引用该属性时会被调用:
and a getter, which is called when referring to the property:
// 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()
.
From Java, the getter can be called as DefaultValues.INSTANCE.getFILES_TO_DOWNLOAD()
or DefaultValues.Companion.getFILES_TO_DOWNLOAD()
respectively.
Non- const
顶级属性被编译为与(1)相同,唯一的区别是现在字段和getter放置在FilenameKt
类中.
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
字段:
But top level const val
is compiled into a public static final
field:
// access flags 0x19
public final static I DEFAULT_FILES_TO_DOWNLOAD = 100
在对象内部声明const val
时,将产生相同的公共static final字段.另外,如果添加> @JvmField
注释(1)中声明的属性.
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).
最后,您可以在object
或顶层使用const
或@JvmField
定义public static final
字段.
Concluding that, you can define public static final
field using const
or @JvmField
either in an object
or at top level.
这篇关于Kotlin中的静态数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!