Junior — Middle
What does the val keyword do to make a variable immutable in code?
sobes.tech AI
Answer from AI
In Kotlin, the keyword val is used to declare a variable whose value cannot be changed after initialization — that is, it is immutable (read-only). This is similar to a constant, but with the ability to initialize at the point of declaration or later (for example, in a constructor).
Example:
val name = "Ivan"
// name = "Peter" // Compilation error: val cannot be reassigned
Using val helps write safer and more predictable code, reducing the likelihood of errors related to changing state.