Sobes.tech
Junior — Middle

How to distinguish a variable declared with var from val and const val in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, the differences between var, val, and const val are as follows:

  • var — a mutable variable. Its value can be changed after initialization.

    var count = 5
    count = 10 // allowed
    
  • val — an immutable variable (a runtime constant). Its value can be assigned only once, but it can be computed at runtime.

    val name = "Alice"
    // name = "Bob" // compile error
    
  • const val — a compile-time constant, whose value is known at compile time. Used only for primitive types and strings, declared at the object or file level.

    const val MAX_COUNT = 100
    

Summary:

  • var — mutable variable.
  • val — immutable variable, its value is set once during execution.
  • const val — immutable constant, its value is known at compile time.
How to distinguish a variable declared with var from… - sobes.tech