Sobes.tech
Junior — Middle

Millised on erinevused võtmesõnade const val ja val vahel Kotlinis?

sobes.tech AI

Vastus AI-lt

In Kotlin, the keyword val denotes an immutable variable (read-only), whose value can be assigned once during initialization, but the value itself can be computed at runtime.

const val is a compile-time constant, which must be of a primitive type or string and initialized with a value known at compile time. Such constants can be used, for example, in annotations or as parameters requiring constants.

Main differences:

  • const val is always a static constant, accessible at the class level (only in objects or at the top level).
  • val is a regular immutable property, which can be computed dynamically.

Example:

const val MAX_COUNT = 10 // compile-time constant
val currentTime = System.currentTimeMillis() // value computed at runtime