In Java, to declare a constant, you do something like:
class Hello {
public static final int MAX_LEN = 20;
}
What is the equivalent in Kotlin?
In Kotlin, we can achieve the functionality of a static method by using a companion identifier. For example, If you want to create a method that will return the address of your company then it is good to make this method static because for every object you create, the address is going to be the same.
Making anything "private" means it is only available from within the class it was defined, "static" makes that variable available from ANYWHERE in that class, and "final" does not allow that variable to be changed, adding the modifier "final" changes your "variable" to a "constant" due to it's constant value instead of ...
By using @JvmStatic annotation Adding @JvmStatic annotation simply before the members to be declared as the equivalent of static ones in Java works well in Kotlin to provide the same functionality.
In Kotlin, we use val to declare an immutable variable and var to declare a mutable variable. You can also optionally specify a type such as String or Int after the variable name. In the example below, we declared a constant firstName of type String with the val keyword.
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
}
}
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
}
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{
}
class Hello {
companion object {
@JvmStatic val MAX_LEN = 20
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With