Values and references

suggest change

Understanding 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:

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:

  1. Structural equality (==, !=): Checks if two objects are equivalent in content. Translates to a?.equals(b) ?: (b === null).
  2. 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:

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:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents