Skip to content
Commitwise
Menu

What is the difference between a value type and a reference type?

LanguagesJunior

In shortAssigning a value type copies the data, so each variable is independent. Assigning a reference type copies a reference, so several variables share one object and see each other's changes.

Model answer

With a value type, the variable holds the data itself. Assigning it or passing it to a function makes a copy, and changing the copy never affects the original. With a reference type, the variable holds a reference to an object; assignment copies the reference, so both variables point to the same object.

struct Point { var x = 0 }        // value type
final class Counter { var n = 0 } // reference type

var a = Point(); var b = a; b.x = 5      // a.x is still 0
let c = Counter(); let d = c; d.n = 5    // c.n is now 5

Per language:

  • Swift: struct, enum, tuples, String and the collections are values (collections use copy-on-write, so copies are cheap until changed). class and actor are references.
  • Kotlin and Java: only primitives (Int, int, Boolean…) behave as values. Everything else, including Kotlin data class and Java record, is a reference type. They get value-like behavior when they’re immutable.

Why it matters: shared mutable objects cause “action at a distance” bugs, where code in one place changes data another place is using. Values (or immutable objects) make that impossible and are safe to share between threads.

What they're looking for

A clear definition with an example of the different behavior after assignment, the right types per language (Swift struct vs class, JVM primitives vs objects), and why it matters for bugs. Bonus for mentioning immutability and copy-on-write.

Common mistakes

  • Saying Kotlin data classes or Java records are value types.
  • Answering only with "stack vs heap", which is about memory, not semantics.
  • Not mentioning what happens when you change a shared object.

More languages questions

Esc

Type to search the whole site.