Let’s learn about the const keyword in kotlin
Variables identified with the const keyword are immutable, as is val. The difference here is that const is applied to variables defined at compile-time. Declaration of a const attribute is just like using the Java static keyword.
Lets first see how ‘val’ works
|
|
I declared a variable with a val keyword and didnt initialize it. The compiler would allow me to do this, i can even initialize the val variable during run time but only once.
|
|
If i try to reinitialize the val variable compiler throws me error “Val can not be reassigned”
Lets see how to declare a const variable in kotlin
|
|
This is similar to static variable in java
|
|
Difference between val and const
The consts are compile time constants. This means that, unlike ‘val’s, their value has to be allocated during the compile time, where as for ‘val’s it can be done at runtime. That means consts can never be assigned to any function or class builder, but only to a string or primitive.I can do something like this for ‘val’
|
|
But i cannot do something like this below, compiler will throw error under const variable like “Const val initializer should be a constant value”
|
|