We use val to create a reference that cannot be changed to point to another object. This helps keep data safe and predictable.
0
0
Val for immutable references in Kotlin
Introduction
When you want to store a value that should not change after it is set.
When you want to avoid accidental changes to a variable in your program.
When you want to make your code easier to understand by showing which values stay the same.
When you want to improve safety by preventing reassignment bugs.
When you want to use constants or fixed references in your program.
Syntax
Kotlin
val name: Type = valueval means the reference cannot be reassigned after initialization.
The object the reference points to can still be mutable if its type allows it.
Examples
This creates an immutable reference to the integer 10.
Kotlin
val number: Int = 10
Type is inferred as String, and the reference cannot be changed.
Kotlin
val name = "Alice"
The reference
list cannot point to a new list, but the list content can change.Kotlin
val list = mutableListOf(1, 2, 3) list.add(4)
Sample Program
This program shows a val holding a string that cannot be changed. It also shows a val holding a mutable list where the content can change but the reference cannot.
Kotlin
fun main() { val greeting = "Hello" println(greeting) // greeting = "Hi" // This would cause an error val numbers = mutableListOf(1, 2, 3) numbers.add(4) println(numbers) }
OutputSuccess
Important Notes
Trying to assign a new value to a val variable will cause a compile error.
val protects the reference, not the object itself.
Use var if you need to change the reference to point to something else.
Summary
val creates an immutable reference that cannot be reassigned.
The object referenced by val can still be mutable if its type allows.
Using val helps make code safer and easier to understand.