161

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?

iknow
  • 6,507
  • 10
  • 30
  • 55
pdeva
  • 39,995
  • 43
  • 129
  • 163

3 Answers3

253

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
    }
}
Ruslan
  • 13,165
  • 8
  • 47
  • 65
  • First example (with const field) can be used for attributes. Popular case: declare all web api paths in the single file and reference it from controllers with such code: "@RequestMapping(path = arrayOf(WebPathConstants.MapApiPath))" (Spring Boot attribute) – Manushin Igor May 24 '17 at 17:27
  • Hi guys! Do you know if this @JvmField is still necessary? I am using this in android and it shows a lint warning saying that "const" can be used instead. I changed it to const and the java class that is using it does not have any problems. – Leandro Ocampo Jan 19 '18 at 19:43
  • 1
    @LeandroOcampo it's still necessary in case if you have mutable static field, `const val` - compile time constant and for sure it can be used as replacement for `@JvmField val` in some cases. Through it doesn't work if value - calculated in runtime, or it not primitive type or String. Ref: http://kotlinlang.org/docs/reference/properties.html#compile-time-constants – Ruslan Jan 19 '18 at 23:08
42

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
}
Gary LO
  • 973
  • 5
  • 11
12

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{
}
Ben Butterworth
  • 13,650
  • 4
  • 61
  • 95
Simon Ludwig
  • 1,587
  • 1
  • 19
  • 26
  • 3
    In the cases where you don't need the constant to be exposed outside the file (ie. java's `private`), this definition is the most concise. – javaxian Apr 25 '18 at 10:27