Kotlin 中 Java 静态最终字段的等价物是什么? [英] What is the equivalent of Java static final fields in Kotlin?
本文介绍了Kotlin 中 Java 静态最终字段的等价物是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Java 中,要声明一个常量,您可以执行以下操作:
In Java, to declare a constant, you do something like:
class Hello {
public static final int MAX_LEN = 20;
}
Kotlin 中的等价物是什么?
What is the equivalent in Kotlin?
推荐答案
根据 Kotlin 文档 这是等效的:
According Kotlin documentation this is equivalent:
class Hello {
companion object {
const val MAX_LEN = 20
}
}
用法:
fun main(srgs: Array<String>) {
println(Hello.MAX_LEN)
}
这也是静态最终属性(带有 getter 的字段):
Also this is static final property (field with getter):
class Hello {
companion object {
@JvmStatic val MAX_LEN = 20
}
}
最后这是静态最终字段:
And finally this is static final field:
class Hello {
companion object {
@JvmField val MAX_LEN = 20
}
}
这篇关于Kotlin 中 Java 静态最终字段的等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文