1. Overview
In this quick tutorial, we’ll discuss static final variables in Java and their equivalent in Kotlin.
In Java, declaring static final variables helps us create constants. And in Kotlin, we have several ways to achieve the same goal.
2. Inside an object
Firstly, let’s take a look at declaring constants in a Kotlin object:
object TestKotlinConstantObject { const val COMPILE_TIME_CONST = 10 val RUN_TIME_CONST: Int init { RUN_TIME_CONST = TestKotlinConstantObject.COMPILE_TIME_CONST + 20; } }
In the above example, we use const val to declare a compile-time constant, and val to declare a run-time constant.
We call them in our Kotlin code in the same way as Java static final variables:
@Test fun givenConstant_whenCompareWithActualValue_thenReturnTrue() { assertEquals(10, TestKotlinConstantObject.COMPILE_TIME_CONST) assertEquals(30, TestKotlinConstantObject.RUN_TIME_CONST) }
Note, though, that we cannot use TestKotlinConstantObject.RUN_TIME_CONST in Java code. The val keyword by itself, without const keyword, doesn’t expose Kotlin fields as public for Java classes to call.
That’s the reason why we have @JvmField to expose val variables to create Java-friendly static final variables:
@JvmField val JAVA_STATIC_FINAL_FIELD = 20
We can call this one just like a const val variable in both Kotlin and Java classes:
assertEquals(20, TestKotlinConstantObject.JAVA_STATIC_FINAL_FIELD)
In addition, we also have @JvmStatic, which we can use in a similar manner to @JvmField. But we’re not using it here since @JvmStatic makes the property accessor static in Java but not the variable itself.
3. Inside a Kotlin class
The declaration of these constants are similar in a Kotlin class, but inside its companion object:
class TestKotlinConstantClass { companion object { const val COMPANION_OBJECT_NUMBER = 40 } }
And we can do the same as before:
assertEquals(40, TestKotlinConstantClass.COMPANION_OBJECT_NUMBER)
5. Conclusion
In this article, we’ve gone through the usage of const, val, and @JvmField in Kotlin to create static final variables.
As always, the code can be found over on GitHub.