In Kotlin there are:
val
- readonly propertyconst val
- compile-time constantsFrom the documentation:
Compile-Time Constants
Properties the value of which is known at compile time can be marked as compile time constants using the
const
modifier. Such properties need to fulfill the following requirements:
- Top-level or member of an object
- Initialized with a value of type String or a primitive type
- No custom getter
Given that kotlin compiler does know to identify initialized values (such as there is no need defining the variable type in an initializer):
const
modifier by itself?In Kotlin, as in other programming languages, properties can be mutable (changeable) or immutable (not changeable). To declare an immutable property, we utilize the terms const and val.
If the value of a read-only (immutable) property is known at the compile time. Mark it as a compile-time constant using the const modifier. Such properties must be fulfilled by the following requirements. Top-level, or member of an object declaration or a companion object.
const val can only be used at the top-level or in object s, while @JvmField can be used on any property.
Both "val" and "const val" are used for declaring read-only properties of a class. The variables declared as const are initialized at the runtime. val deals with the immutable property of a class, that is, only read-only variables can be declared using val. val is initialized at the runtime.
The const
modifier seriously changes the contract of a property.
For example, if you have a regular property, you may add a special getter to it without affecting the code which uses it.
On the other hand, you would have to recompile the user code in order to remove const
and add getters. In other words, you loose the advantage of having a property over a field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With