Skip to content

Using (val) and (const val) in Kotlin

Devrath edited this page Feb 10, 2024 · 2 revisions

Usage of val in kotlin

  • 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 avoid side-effects in kotlin that would lead to bugs.

Usage of const val in kotlin

  • 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 or strings in the const val.
  • const val in kotlin is equivalent to static final in Java.

Why is there a possible need for (const val) when you can use just (val)

  • 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.
Clone this wiki locally