In Java, to declare a constant, you do something like:
class Hello {
public static final int MAX_LEN = 20;
}
What is the equivalent in Ko
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
}
}
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
val MIN_LENGTH = 10
class MyService{
}
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
}