0
0
Kotlinprogramming~15 mins

Var for mutable references in Kotlin - Deep Dive

Choose your learning style9 modes available
Overview - Var for mutable references
What is it?
In Kotlin, 'var' is a keyword used to declare variables whose values can change after they are first set. Unlike 'val', which creates a read-only reference, 'var' allows you to update the variable to point to a different value or object. This means you can reassign new data to a 'var' variable anytime during the program.
Why it matters
Without mutable references like 'var', programs would be very limited because you couldn't change data once set, making it hard to handle real-world situations where information changes over time. 'var' lets you write flexible and dynamic code that can respond to user input, calculations, or other changing conditions.
Where it fits
Before learning about 'var', you should understand basic Kotlin syntax and the difference between variables and constants. After mastering 'var', you can explore deeper topics like data mutability, object references, and Kotlin's type system.
Mental Model
Core Idea
'var' is like a labeled box whose contents you can replace anytime, while 'val' is a box sealed after first use.
Think of it like...
Imagine a mailbox labeled with your name. If it's a 'var' mailbox, you can change the letters inside anytime you want. If it's a 'val' mailbox, once you put a letter inside and seal it, you can't change what's inside anymore.
┌─────────────┐
│  var box    │
│  Contents:  │
│  [apple]    │
│  (can swap) │
└─────────────┘

vs.

┌─────────────┐
│  val box    │
│  Contents:  │
│  [apple]    │
│  (fixed)    │
└─────────────┘
Build-Up - 6 Steps
1
FoundationDeclaring variables with var
🤔
Concept: Learn how to create a mutable variable using 'var' in Kotlin.
In Kotlin, you declare a mutable variable by writing 'var' followed by the variable name and its value. Example: var age = 25 This means 'age' can be changed later in the code.
Result
The variable 'age' holds the value 25 and can be updated.
Understanding how to declare mutable variables is the first step to writing flexible programs that can change data as needed.
2
FoundationDifference between var and val
🤔
Concept: Understand the key difference between mutable ('var') and immutable ('val') variables.
Using 'val' creates a variable that cannot be reassigned after initialization. Example: val name = "Alice" // name = "Bob" // This will cause an error Using 'var' allows reassignment: var score = 10 score = 20 // This is allowed
Result
You see that 'val' variables are fixed, while 'var' variables can change.
Knowing this difference helps you decide when to allow changes and when to protect data from accidental modification.
3
IntermediateMutable references with objects
🤔
Concept: Learn how 'var' works with objects and references, not just simple values.
When you declare an object with 'var', you can change which object the variable points to. Example: var list = mutableListOf(1, 2, 3) list = mutableListOf(4, 5) // Allowed But if declared with 'val': val list = mutableListOf(1, 2, 3) // list = mutableListOf(4, 5) // Error However, you can still modify the contents of the list even if declared with 'val'.
Result
You can reassign 'var' variables to new objects, but 'val' variables cannot be reassigned.
Understanding that 'var' controls the reference itself, not the object's mutability, clarifies how Kotlin manages data.
4
IntermediateReassigning var variables safely
🤔Before reading on: Do you think reassigning a 'var' variable affects all references to the original object? Commit to your answer.
Concept: Explore how reassigning a 'var' variable changes only that variable's reference, not other references to the same object.
Consider: var a = mutableListOf(1, 2) var b = a a = mutableListOf(3, 4) Now, 'a' points to a new list, but 'b' still points to the original list [1, 2]. Reassigning 'a' does not affect 'b'.
Result
'a' and 'b' refer to different lists after reassignment.
Knowing that 'var' changes the reference itself, not the object, prevents confusion about shared data and side effects.
5
AdvancedVar with nullable types and reassignment
🤔Before reading on: Can a 'var' variable declared as nullable be assigned null later? Commit to your answer.
Concept: Learn how 'var' works with nullable types and how reassignment to null is allowed if the type permits.
Example: var message: String? = "Hello" message = null // Allowed because type is nullable If the type was non-nullable: var text: String = "Hi" // text = null // Error This shows 'var' allows changing the value, but type rules still apply.
Result
'message' can hold a string or null, and can be reassigned accordingly.
Understanding how 'var' interacts with Kotlin's null safety helps avoid runtime errors and write safer code.
6
ExpertVar and thread safety considerations
🤔Before reading on: Do you think using 'var' variables is always safe in multi-threaded Kotlin programs? Commit to your answer.
Concept: Explore how mutable 'var' variables can cause issues in concurrent environments without proper synchronization.
In multi-threaded programs, if multiple threads change a 'var' variable without coordination, data races and inconsistent states can occur. Example: var counter = 0 // Multiple threads incrementing counter without locks can cause errors To fix this, use synchronization tools like 'AtomicInteger' or 'synchronized' blocks.
Result
Using 'var' in concurrent code requires care to avoid bugs.
Knowing the limits of 'var' in concurrency prevents subtle, hard-to-find bugs in real-world applications.
Under the Hood
'var' variables in Kotlin are references stored in memory locations that can be updated to point to new values or objects. At runtime, the JVM manages these references, allowing the variable to hold different data over time. The variable name acts as a pointer to the current value, and reassigning 'var' changes this pointer without altering the original object unless the object itself is mutable.
Why designed this way?
Kotlin was designed to balance safety and flexibility. Immutable references ('val') encourage safer code by preventing accidental changes, while mutable references ('var') provide the flexibility needed for real-world programming. This design helps developers choose the right tool for their needs, improving code clarity and reducing bugs.
┌───────────────┐       ┌───────────────┐
│  var variable │──────▶│  Object in    │
│  (reference)  │       │  memory       │
└───────────────┘       └───────────────┘

Reassigning 'var' changes the arrow to point to a new object.

val variable ──▶ fixed object (cannot change arrow)
Myth Busters - 3 Common Misconceptions
Quick: Does declaring a 'var' variable mean the object it points to is always mutable? Commit to yes or no.
Common Belief:Many think that if a variable is declared with 'var', the object it holds must be mutable.
Tap to reveal reality
Reality:The 'var' keyword only means the reference can change to point to a different object; the object itself can be immutable or mutable regardless.
Why it matters:Confusing reference mutability with object mutability can lead to incorrect assumptions about data safety and cause bugs when modifying supposedly immutable objects.
Quick: If you reassign a 'var' variable, do all other variables referencing the original object also change? Commit to yes or no.
Common Belief:Some believe reassigning a 'var' variable updates all references to the same object automatically.
Tap to reveal reality
Reality:Reassigning a 'var' variable only changes that variable's reference; other variables still point to the original object.
Why it matters:Misunderstanding this can cause unexpected behavior when multiple references to the same object exist, leading to bugs in data handling.
Quick: Is using 'var' always safe in multi-threaded Kotlin programs? Commit to yes or no.
Common Belief:Many assume 'var' variables are safe to use freely in any context, including multi-threading.
Tap to reveal reality
Reality:'var' variables are not thread-safe by default; concurrent modifications without synchronization can cause data races and inconsistent states.
Why it matters:Ignoring thread safety can cause subtle, hard-to-debug errors in concurrent applications, risking data corruption.
Expert Zone
1
Reassigning a 'var' variable changes only the reference, not the object's internal state, which can be mutable or immutable independently.
2
Using 'var' with Kotlin's smart casts requires care because reassignments can invalidate assumptions about variable types.
3
In inline functions and lambdas, 'var' variables captured by closures behave differently, affecting mutability and lifecycle.
When NOT to use
Avoid using 'var' when you want to guarantee immutability and thread safety; prefer 'val' or immutable data structures. For concurrent mutable state, use atomic types or synchronization primitives instead of plain 'var'.
Production Patterns
In production Kotlin code, 'var' is often used for local variables that need updating, loop counters, or temporary state. Immutable 'val' is preferred for class properties and function parameters to reduce bugs. Advanced patterns use 'var' with careful synchronization or in combination with Kotlin's coroutines for safe concurrency.
Connections
Immutable Data Structures
Opposite concept
Understanding 'var' helps clarify why immutable data structures are valuable for safety and predictability, as they prevent changes even if references are mutable.
Pointers in C/C++
Similar pattern
Like 'var' references in Kotlin, pointers in C/C++ can be reassigned to different memory addresses, separating the idea of changing the reference from changing the data.
Version Control Systems
Conceptual analogy
Just as 'var' allows changing what a variable points to, version control lets you switch between different versions of code, highlighting the importance of managing references and changes carefully.
Common Pitfalls
#1Assuming 'var' means the object is mutable and safe to change.
Wrong approach:var name = "Alice" name[0] = 'B' // Trying to change string content directly
Correct approach:var name = "Alice" name = "Bob" // Reassigning the whole string instead
Root cause:Strings in Kotlin are immutable; 'var' only allows changing the reference, not the object's internal state.
#2Reassigning a 'var' variable expecting all references to update.
Wrong approach:var a = mutableListOf(1, 2) var b = a a = mutableListOf(3, 4) println(b) // Expecting b to be [3,4]
Correct approach:var a = mutableListOf(1, 2) var b = a a.clear() a.addAll(listOf(3, 4)) println(b) // b is now [3,4]
Root cause:Reassignment changes only the variable's reference, not other variables pointing to the original object.
#3Using 'var' variables in multi-threaded code without synchronization.
Wrong approach:var counter = 0 // Multiple threads increment counter without locks
Correct approach:val counter = AtomicInteger(0) counter.incrementAndGet() // Thread-safe increment
Root cause:'var' variables are not thread-safe by default; concurrent access requires special handling.
Key Takeaways
'var' declares a mutable reference that can point to different values or objects over time.
The mutability of the reference ('var') is separate from the mutability of the object it points to.
Reassigning a 'var' variable changes only that variable's reference, not other references to the same object.
Using 'var' requires care in multi-threaded environments to avoid data races and inconsistent states.
Choosing between 'var' and 'val' helps write clearer, safer, and more maintainable Kotlin code.