-
Notifications
You must be signed in to change notification settings - Fork 22
Using (val) and (const val) in Kotlin
Devrath edited this page Feb 10, 2024
·
2 revisions
- We use
val
to declare read-only data in kotlin. - It is also called
assign once
values. - You should always strive to use
val
to avoidside-effects
in kotlin that would lead to bugs.
- We use
const val
to declare the constants in kotlin. - If we have a value that never changes and the value is known at compile time, we should strive to use
const val
. - We can add only
primitive type
orstrings
in theconst val
. -
const val
in kotlin is equivalent tostatic final
in Java.
- Using the
const val
helps the compiler to do optimizations during the compile time itself. - Also it's good to know that there is a value that does not change even during the runtime.