When we try to use Kotlin as a development language, we should think about how to define a constant in Kotlin, as in Java code like this
|
|
In Kotlin, two simple keywords are provided, one var and the other val
- Var stands for ordinary mutable variables, readable and writable
- Val is represented as a read-only variable. The Java equivalent of a final variable
|
|
So the val modifier is Kotlin’s constant
Many people have mistakenly assumed that val is a constant in Kotlin, and then it is not, as in the following implementation
|
|
The value we get above currentTimeMillis is changing every time we access it, so it’s not constant.
Why?
This is because in Kotlin, a var generates two corresponding methods, getter and setter methods, for example
|
|
The resulting bytecode will contain the following two methods and a backing field
|
|
For val, only one corresponding GET method is generated, for example
|
|
The generated bytecode will contain methods like this
|
|
How do you generate true constants
There are two ways to implement true constants: one is const, and the other is using the @jVMField annotation
const
Const, as its name implies, is short for constant. You can use it to declare constants, but only in top-level and object.
|
|
- A top-level is the outermost part of the code file, such as common classes (non-inner and nested) at the top level. Structurally constants do not belong to any class, but to files.
- Object can refer to the most external object or to the companion object.
@JvmField
- A val constant can be made constant by adding an @jVMField in front of it.
- Its internal effect is to inhibit the compiler from generating the corresponding getter method
- The get method of val cannot be overridden if it is decorated with this annotation
The sample is as follows
|
|
As for Kotlin’s constant study, the most effective method is to analyze bytecode and decomcompile comparative learning. For more information on how to learn Kotlin you can read this article to study some ways to learn Kotlin