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

JavaKotlin

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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 - Java

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 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpdevaView Question on Stackoverflow
Solution 1 - JavaRuslanView Answer on Stackoverflow
Solution 2 - JavaGary LOView Answer on Stackoverflow
Solution 3 - JavaSimon LudwigView Answer on Stackoverflow