Values and references
suggest changeUnderstanding how Kotlin handles values, references, mutability, and memory equality is fundamental to writing safe, idiomatic code.
Kotlin unifies primitive and reference types under a single object-oriented hierarchy while delivering low-level JVM primitive performance whenever possible.
val vs var: Reference Reassignment
In Kotlin:
valdeclares a read-only reference (assigned once, cannot be reassigned).vardeclares a mutable reference (can be reassigned to a different value of the same type).
fun main() {
val birthYear = 1995
// birthYear = 1996 // Compile error: 'val' cannot be reassigned
var currentAge = 30
currentAge = 31 // Valid: var reference can change
}
Reference Immutability vs Object Immutability
Declaring a variable with val only makes the reference immutable—it does not make the underlying object immutable:
// The reference 'tags' cannot point to a new list
val tags = mutableListOf("kotlin", "jvm")
// But the object referenced by 'tags' CAN be mutated!
tags.add("android")
println(tags) // [kotlin, jvm, android]
// tags = mutableListOf("new") // Compile error: 'val' cannot be reassigned
To achieve true immutability, pair val with read-only collection interfaces (List, Set, Map instead of MutableList, MutableSet, MutableMap):
val immutableTags: List<String> = listOf("kotlin", "jvm")
// immutableTags.add(...) // Compile error: unresolved reference 'add'
Structural Equality (==) vs Referential Equality (===)
Kotlin distinguishes between comparing values and comparing memory addresses:
- Structural equality (
==,!=): Checks if two objects are equivalent in content. Translates toa?.equals(b) ?: (b === null). - Referential equality (
===,!==): Checks if two references point to the exact same object in memory.
data class Point(val x: Int, val y: Int)
fun main() {
val p1 = Point(10, 20)
val p2 = Point(10, 20)
val p3 = p1
// Structural equality (content comparison)
println(p1 == p2) // true: both have x=10, y=20
println(p1 != p2) // false
// Referential equality (memory identity comparison)
println(p1 === p2) // false: separate heap allocations
println(p1 === p3) // true: p3 points to the exact same instance as p1
}
Primitives and JVM Boxing
Unlike Java, Kotlin has no separate primitive keywords like int or boolean. Types like Int, Double, and Boolean look like regular classes.
At compile-time:
- Non-nullable primitives (
Int,Double) are compiled directly to primitive JVM types (int,double) with zero overhead. - Nullable primitives (
Int?) or primitives in generic collections (List<Int>) are boxed into objects (java.lang.Integer).
fun main() {
val a: Int = 1000
val b: Int = 1000
println(a == b) // true
println(a === b) // true (unboxed primitives; compiler warns identity equality on Int is deprecated)
val boxedA: Int? = 1000
val boxedB: Int? = 1000
println(boxedA == boxedB) // true (equals compares integer values)
println(boxedA === boxedB) // false (distinct boxed Integer objects; compiler warns this is prohibited)
}
Note: The JVM caches small integers between -128 and 127. For integers within this range, boxed references may share identical instances due to the JVM Integer cache.
Pass-by-Value Semantics
In Kotlin, function arguments are strictly passed by value:
- For primitive values, the value itself is copied.
- For objects, the reference value (pointer) is copied.
- Function parameters in Kotlin are implicitly
valand cannot be reassigned within the function body.
class Counter(var count: Int)
fun update(num: Int, counter: Counter) {
// num = 20 // Compile error: 'val' cannot be reassigned
// Mutating the object through its copied reference affects the original instance
counter.count += num
}
fun main() {
val c = Counter(10)
update(5, c)
println(c.count) // 15
}
Value Classes (@JvmInline value class)
Value classes (introduced in Kotlin 1.5) wrap an underlying primitive or reference without incurring heap allocation overhead. The compiler inlines the wrapped value wherever possible:
@JvmInline
value class UserId(val rawId: Long)
@JvmInline
value class Email(val address: String) {
init {
require(address.contains("@")) { "Invalid email address" }
}
}
fun sendEmail(userId: UserId, email: Email) {
println("Sending email to user ${userId.rawId} at ${email.address}")
}
fun main() {
val id = UserId(1001L)
val email = Email("user@example.com")
sendEmail(id, email)
// At runtime, id is a primitive 'long' and email is a 'java.lang.String'
}
Best Practices
- Default to
val: Make every property and local variablevalunless you explicitly require reassignment. - Prefer immutable data structures: Use read-only collections and
data classwithcopy()to prevent accidental state mutation across threads. - Use
==for comparisons: Rely on structural equality (==) in business logic; reserve referential equality (===) for performance optimizations or identity-based checks. - Leverage
@JvmInline value classfor domain IDs: Create domain-specific types (likeOrderId,Cents) with zero memory allocation penalty.