What is the equivalent of Java static final fields in Kotlin?
Solution 1:
According Kotlin documentation this is equivalent:
class Hello {
companion object {
const val MAX_LEN = 20
}
}
Usage:
fun main(srgs: Array<String>) {
println(Hello.MAX_LEN)
}
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
}
}
Solution 2:
if you have an implementation in Hello
, use companion object
inside a class
class Hello {
companion object {
val MAX_LEN = 1 + 1
}
}
if Hello
is a pure singleton object
object Hello {
val MAX_LEN = 1 + 1
}
if the properties are compile-time constants, add a const
keyword
object Hello {
const val MAX_LEN = 20
}
if you want to use it in Java, add @JvmStatic
annotation
object Hello {
@JvmStatic val MAX_LEN = 20
}
Solution 3:
For me
object Hello {
const val MAX_LEN = 20
}
was to much boilerplate. I simple put the static final fields above my class like this
private val MIN_LENGTH = 10 // <-- The `private` scopes this variable to this file. Any class in the file has access to it.
class MyService{
}