Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of Java static final fields in Kotlin?

Tags:

java

kotlin

People also ask

What is the Java equivalent of static in Kotlin?

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.

Does Kotlin have static methods?

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.

What is a static variable in Kotlin?

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.

Do we have anything called static in Kotlin?

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{
}