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 Java, once a method is declared as "static", it can be used in different classes without creating an object. With static methods, we don't have to create the same boilerplate code for each and every class.
AndroidMobile DevelopmentApps/ApplicationsKotlin. In Java, "static" keyword is used for efficient memory management. Once a variable or method is declared as static, then the JVM will allocate memory for these variable only once.
One way in which the Kotlin language differs from Java is that Kotlin doesn't contain the static keyword that we're familiar with. In this quick tutorial, we'll see a few ways to achieve Java's static method behavior in Kotlin.
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{
}
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