In Kotlin, variables can be either mutable or immutable. The distinction between these two types is fundamental to how values can be managed and modified within a program.
Mutable Variables (var)
A mutable variable is declared with the var keyword. This means that the variable's value can be changed after its initial assignment.
var mutableVariable = 10
mutableVariable = 20 // This is allowed
println(mutableVariable) // Prints: 20
Immutable Variables (val)
An immutable variable is declared with the val keyword. This means that the variable's value cannot be changed after it has been assigned. Essentially, it is a read-only variable.
val immutableVariable = 10
// immutableVariable = 20 // This is not allowed and will cause a compilation error
println(immutableVariable) // Prints: 10
Key Differences
Reassignment:
var: Allows reassignment of values.
val: Does not allow reassignment of values after initial assignment.
Use Cases:
var: Use when the variable needs to change its value during the program execution.
val: Use when the variable should remain constant, enhancing code reliability and readability.
Important Considerations
Immutable Objects: If val is used with a mutable object (like a list or a custom object), the reference cannot be changed, but the object’s state can still be modified.
val list = mutableListOf(1, 2, 3)
// list = mutableListOf(4, 5, 6) // This is not allowed
list.add(4) // This is allowed
println(list) // Prints: [1, 2, 3, 4]
Read-Only Collections: Kotlin provides read-only collections which can be declared using val to ensure the collections themselves cannot be modified.
val readOnlyList = listOf(1, 2, 3)
// readOnlyList.add(4) // This is not allowed
println(readOnlyList) // Prints: [1, 2, 3]
val readOnlyList = listOf(1, 2, 3)
// readOnlyList.add(4) // This is not allowed
println(readOnlyList) // Prints: [1, 2, 3]
val readOnlyList = listOf(1, 2, 3)
// readOnlyList.add(4) // This is not allowed
println(readOnlyList) // Prints: [1, 2, 3]
Example of Mutability in Custom Objects
data class Person(var name: String, val age: Int)
fun main() {
val person = Person("Alice", 30)
person.name = "Bob" // Allowed, because `name` is a var
// person.age = 31 // Not allowed, because `age` is a val
println(person) // Prints: Person(name=Bob, age=30)
}
In this example, the name property can be changed because it is declared with var, while the age property cannot be changed because it is declared with val.
Understanding when to use var and val is crucial in Kotlin for writing clear, maintainable, and safe code. Using val by default is generally recommended, switching to var only when mutability is necessary.
#android
#coding
#androidcoding
#programming
#androidprogramming
#kotlin
#kotlintutorial