Structs, tuples, and records
suggest changeKotlin has no struct, tuple or record keyword. Instead it covers all three with a few tools:
data class: a named record with typed fields. The compiler generatesequals(),hashCode(),toString(),copy()andcomponentN()functions. This is what you use in place of a C struct, a Java record or a Python dataclass.PairandTriple: generic tuples with two or three elements, from the standard library.- Destructuring declarations: unpack a data class or a pair into separate variables, the way you unpack a tuple in other languages.
value class: a wrapper around a single value that usually costs nothing at runtime.@JvmRecord: makes a data class compile to a real Java record.
This article shows each of them and when to use which. For copy() in depth see Copying and cloning, and for making records really immutable see Immutability.
data class: the record type
Add data in front of a class whose primary constructor declares properties:
data class Point(val x: Int, val y: Int)
fun main() {
val a = Point(1, 2)
val b = Point(1, 2)
println(a) // toString()
println(a == b) // equals() compares properties
println(a === b) // but they are different objects
println(a.hashCode() == b.hashCode())
println(setOf(a, b).size) // equal values collapse in a set
val c = a.copy(y = 5) // copy() with one property changed
println(c)
val (x, y) = c // component1(), component2()
println("x=$x y=$y")
}
Point(x=1, y=2)
true
false
true
1
Point(x=1, y=5)
x=1 y=5
Point is a regular class, but because it is a data class the compiler generated:
toString()that prints the class name and every propertyequals()andhashCode()that compare property values, so equal points work as map keys and set elementscopy()that creates a new instance with some properties changedcomponent1(),component2(), ... used by destructuring
a == b calls equals() and compares content. a === b checks whether both variables point to the same object. See Equality Identity for more about the two operators.
A data class has a few rules:
- the primary constructor needs at least one parameter, and every parameter must be a
valorvar - it can't be
abstract,open,sealedorinner - it can implement interfaces and extend other classes
Only constructor properties count
The generated functions use only the properties declared in the primary constructor. Properties declared in the class body are ignored:
data class User(val name: String, val email: String) {
var loginCount: Int = 0 // declared in the body
val domain: String get() = email.substringAfter('@')
}
fun main() {
val u1 = User("ann", "ann@example.com")
val u2 = User("ann", "ann@example.com")
u1.loginCount = 10
println(u1) // loginCount is not in toString()
println(u1 == u2) // nor in equals()
println(u1.copy().loginCount) // and copy() resets it
println(u1.domain)
}
User(name=ann, email=ann@example.com)
true
0
example.com
This is useful for derived or cached values such as domain, but it surprises people who add a mutable field to the body and expect it in equals(). If a property is part of the value, put it in the constructor.
Validation and custom members
A data class can have an init block, methods and overrides. If you write toString(), equals() or hashCode() yourself, the compiler uses your version:
data class Product(val sku: String, val name: String, val price: Double) {
init {
require(price >= 0) { "price must not be negative: $price" }
}
// Override toString() to keep long or sensitive data out of logs
override fun toString() = "Product($sku)"
}
data class Credentials(val user: String, private val password: String) {
fun check(input: String) = input == password
}
fun main() {
val p = Product("A-1", "Keyboard", 49.99)
println(p)
println(p.copy(price = 39.99).price)
try {
p.copy(price = -1.0) // copy() runs init too
} catch (e: IllegalArgumentException) {
println(e.message)
}
val c = Credentials("ann", "s3cret")
println(c) // private properties are still printed
println(c.check("s3cret"))
}
Product(A-1)
39.99
price must not be negative: -1.0
Credentials(user=ann, password=s3cret)
true
Things to note:
copy()calls the primary constructor, soinitvalidation runs for copies too- a
privateconstructor property is still part oftoString(),equals()andcopy(). OverridetoString()to keep secrets out of logs - you can't override
copy()or thecomponentN()functions
Destructuring declarations
Destructuring unpacks an object into several variables in one statement. It works with anything that has component1(), component2(), ... functions, which data classes, Pair, Triple, Map.Entry and lists get for free:
data class Order(val id: Int, val customer: String, val total: Double)
fun main() {
val order = Order(7, "ann", 120.5)
val (id, customer, total) = order
println("$id $customer $total")
// Skip components you don't need with _
val (_, who) = order
println(who)
val orders = listOf(order, Order(8, "bob", 40.0))
// In for loops
for ((orderId, name) in orders) {
println("#$orderId by $name")
}
// In lambda parameters (note the parentheses)
val big = orders.filter { (_, _, t) -> t > 100 }.map { (i, _, _) -> i }
println(big)
// Map entries destructure into key and value
val totals = orders.associate { it.customer to it.total }
for ((name, sum) in totals) println("$name: $sum")
totals.forEach { (name, sum) -> println("$name -> $sum") }
}
7 ann 120.5
ann
#7 by ann
#8 by bob
[7]
ann: 120.5
bob: 40.0
ann -> 120.5
bob -> 40.0
The _ placeholder skips a component without calling its componentN() function. In a lambda, { (a, b) -> ... } destructures one parameter, while { a, b -> ... } declares two separate parameters, so the parentheses matter.
Positional destructuring is fragile
Classic destructuring is by position, not by name. If the order of constructor properties changes, code that destructures the class still compiles but reads the wrong values:
// Version 1 of a class
// data class Range(val start: Int, val end: Int)
// Version 2: someone added a property at the front
data class Range(val label: String, val start: Int, val end: Int)
fun main() {
val r = Range("week", 1, 7)
// Written against version 1. Still compiles, but now
// `start` is the label and `end` is the start.
val (start, end) = r
println("start=$start end=$end")
// Accessing properties by name is immune to reordering
println("start=${r.start} end=${r.end}")
}
start=week end=1
start=1 end=7
The variable names start and end mean nothing to the compiler. Destructuring is safest for small, stable types such as Pair, map entries or local results. For public data classes with many properties, access properties by name.
Kotlin is fixing this with name-based destructuring, where (val ...) declarations match properties by name. In Kotlin 2.4 it is experimental and needs the -Xname-based-destructuring=complete compiler flag (without it the compiler says the feature is available since language version 2.5):
data class Range(val label: String, val start: Int, val end: Int)
fun main() {
val r = Range("week", 1, 7)
// Matched by property name, not by position
(val end, val start) = r
println("start=$start end=$end")
// Rename while destructuring
(val from = start, val to = end) = r
println("$from..$to")
}
start=1 end=7
1..7
Pair and Triple: tuples
Pair<A, B> and Triple<A, B, C> are generic data classes from the standard library. The infix function to creates a Pair:
fun minMax(nums: List<Int>): Pair<Int, Int> = nums.min() to nums.max()
fun main() {
val p: Pair<String, Int> = "answer" to 42 // infix `to` builds a Pair
println(p)
println("${p.first} ${p.second}")
val (lo, hi) = minMax(listOf(5, 3, 9, 1))
println("lo=$lo hi=$hi")
val t = Triple("ann", 30, true)
println(t)
val (name, age, active) = t
println("$name $age $active")
// Pair and Triple are data classes: equality, copy(), toList()
println(p == ("answer" to 42))
println(p.copy(second = 43))
println(t.toList())
// Map entries are often built from pairs
val ages = mapOf("ann" to 30, "bob" to 25)
println(ages)
println(ages.toList()) // List<Pair<String, Int>>
// zip, partition and unzip return pairs
val (even, odd) = (1..6).partition { it % 2 == 0 }
println("even=$even odd=$odd")
val zipped = listOf("a", "b").zip(listOf(1, 2))
println(zipped)
println(zipped.unzip())
}
(answer, 42)
answer 42
lo=1 hi=9
(ann, 30, true)
ann 30 true
true
(answer, 43)
[ann, 30, true]
{ann=30, bob=25}
[(ann, 30), (bob, 25)]
even=[2, 4, 6] odd=[1, 3, 5]
[(a, 1), (b, 2)]
([a, b], [1, 2])
There is no Tuple4 or larger. Many standard functions use pairs: mapOf takes them, Map.toList(), zip and partition return them, and unzip turns a list of pairs into a pair of lists.
Prefer a named data class
first and second say nothing about what the values mean. Use a pair for short-lived, obvious combinations, such as a key and a value or a min and a max. When a result is returned from a public function or has more than two parts, declare a data class. It takes one line:
// Hard to read at the call site: which Double is which?
fun statsPair(xs: List<Double>): Pair<Double, Double> =
xs.average() to xs.maxOf { it }
// A small data class names the result
data class Stats(val mean: Double, val max: Double, val count: Int)
fun stats(xs: List<Double>) = Stats(xs.average(), xs.maxOf { it }, xs.size)
fun main() {
val xs = listOf(2.0, 4.0, 9.0)
val p = statsPair(xs)
println("${p.first} ${p.second}") // first? second?
val s = stats(xs)
println("mean=${s.mean} max=${s.max} n=${s.count}")
println(s)
val (mean, max) = s // destructuring still works
println("$mean $max")
}
5.0 9.0
mean=5.0 max=9.0 n=3
Stats(mean=5.0, max=9.0, count=3)
5.0 9.0
The data class makes call sites readable and lets you add a field later without changing every caller's types. It also prevents mixing up two values of the same type, which a Pair<Double, Double> doesn't.
Ad-hoc records inside a function
When you need a record type in one function only, you can declare a local data class. For a single result with named fields you can also return an anonymous object from a private function:
fun report(lines: List<String>) {
// A data class declared inside a function is visible only here
data class WordCount(val word: String, val count: Int)
val counts = lines
.flatMap { it.lowercase().split(" ") }
.groupingBy { it }
.eachCount()
.map { (w, c) -> WordCount(w, c) }
.sortedWith(compareByDescending<WordCount> { it.count }.thenBy { it.word })
counts.take(3).forEach(::println)
}
private fun parse(line: String) = object {
val key = line.substringBefore('=').trim()
val value = line.substringAfter('=').trim()
}
fun main() {
report(listOf("the cat", "the dog", "a cat"))
// Anonymous object: typed properties without declaring a class.
// Works because parse() is private, so its return type stays anonymous.
val kv = parse("port = 8080")
println("${kv.key} -> ${kv.value}")
}
WordCount(word=cat, count=2)
WordCount(word=the, count=2)
WordCount(word=a, count=1)
port -> 8080
A local data class doesn't leak into the rest of the code, and you still get toString() and equals(). Anonymous objects are only typed this way when the function or property returning them is private or local; from a public function the return type would be Any.
Sum types: sealed data classes and data objects
A struct holds several fields at once. Often you also need a value that is one of several shapes. In Kotlin you model that with a sealed interface implemented by data classes. A case without fields is a data object, which gets a readable toString():
sealed interface Shape
data class Circle(val radius: Double) : Shape
data class Rect(val width: Double, val height: Double) : Shape
data object Empty : Shape
fun area(s: Shape): Double = when (s) {
is Circle -> Math.PI * s.radius * s.radius
is Rect -> s.width * s.height
Empty -> 0.0
}
fun describe(s: Shape) = when (s) {
is Rect if s.width == s.height -> "square ${s.width}"
is Rect -> "rect ${s.width}x${s.height}"
is Circle -> "circle r=${s.radius}"
Empty -> "nothing"
}
fun main() {
val shapes = listOf(Circle(1.0), Rect(2.0, 3.0), Rect(2.0, 2.0), Empty)
for (s in shapes) {
println("$s area=${"%.2f".format(area(s))} ${describe(s)}")
}
}
Circle(radius=1.0) area=3.14 circle r=1.0
Rect(width=2.0, height=3.0) area=6.00 rect 2.0x3.0
Rect(width=2.0, height=2.0) area=4.00 square 2.0
Empty area=0.00 nothing
when is exhaustive over a sealed hierarchy, so the compiler reports an error if you add a new shape and forget to handle it. The is Rect if ... branch is a guard condition, stable since Kotlin 2.2.
Ordering records
Data classes don't generate compareTo(). To sort them, pass a comparator built with compareBy or implement Comparable:
data class Version(val major: Int, val minor: Int, val patch: Int) : Comparable<Version> {
override fun compareTo(other: Version) = comparator.compare(this, other)
override fun toString() = "$major.$minor.$patch"
companion object {
private val comparator =
compareBy<Version>({ it.major }, { it.minor }, { it.patch })
fun parse(s: String): Version {
val (a, b, c) = s.split('.').map(String::toInt)
return Version(a, b, c)
}
}
}
fun main() {
val versions = listOf("1.10.0", "1.2.3", "1.2.10", "0.9.9").map(Version::parse)
println(versions.sorted())
println(versions.max())
println(Version.parse("2.0.0") > Version(1, 99, 99))
}
[0.9.9, 1.2.3, 1.2.10, 1.10.0]
1.10.0
true
compareBy with several selectors compares field by field, which is what you usually want for records. Note also val (a, b, c) = ... on a list: lists support destructuring of their first five elements. See Sorting for more about comparators.
Nested records
Equality, hashCode() and toString() work recursively for properties that are data classes or collections, because those types implement content equality themselves:
data class Address(val city: String, val zip: String)
data class Person(val name: String, val address: Address, val tags: List<String>)
fun main() {
val a = Person("ann", Address("Oslo", "0150"), listOf("admin"))
val b = Person("ann", Address("Oslo", "0150"), listOf("admin"))
println(a == b) // nested data classes and lists compare by content
println(a)
// "Change" a nested field: copy at every level
val moved = a.copy(address = a.address.copy(city = "Bergen"))
println(moved.address)
println(a.address)
}
true
Person(name=ann, address=Address(city=Oslo, zip=0150), tags=[admin])
Address(city=Bergen, zip=0150)
Address(city=Oslo, zip=0150)
copy() is shallow, so updating a nested field requires a copy() at every level. If this becomes painful, flatten the structure or write a helper function on the outer class.
Pitfalls
Mutable properties in hash-based collections
A data class with var properties computes hashCode() from their current values. If you change an object while it's in a HashSet or used as a HashMap key, the collection can no longer find it:
data class Tag(var name: String)
fun main() {
val tag = Tag("kotlin")
val tags = hashSetOf(tag)
tag.name = "java" // changes hashCode()
println(tags)
println(tag in tags) // looks in the wrong bucket
println(tags.contains(Tag("java")))
println(tags.any { it == tag }) // linear scan still finds it
}
[Tag(name=java)]
false
false
true
The object is still in the set, but contains() looks in the bucket for the new hash code. Prefer val properties for data classes, and create changed versions with copy().
Arrays compare by identity
Arrays don't override equals(), so a data class holding an array compares the array references, not the contents. The IDE warns about this. Either override equals() and hashCode() with contentEquals() and contentHashCode(), or use a List:
data class Packet(val id: Int, val payload: ByteArray)
data class Packet2(val id: Int, val payload: ByteArray) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Packet2) return false
return id == other.id && payload.contentEquals(other.payload)
}
override fun hashCode(): Int = 31 * id + payload.contentHashCode()
override fun toString() = "Packet2(id=$id, payload=${payload.contentToString()})"
}
data class Packet3(val id: Int, val payload: List<Byte>)
fun main() {
val bytes = byteArrayOf(1, 2, 3)
println(Packet(1, bytes) == Packet(1, bytes.copyOf()))
println(Packet(1, bytes))
println(Packet2(1, bytes) == Packet2(1, bytes.copyOf()))
println(Packet2(1, bytes))
println(Packet3(1, listOf(1, 2)) == Packet3(1, listOf(1, 2)))
}
false
Packet(id=1, payload=[1, 2, 3])
true
Packet2(id=1, payload=[1, 2, 3])
true
The generated toString() does print array contents, so the problem is easy to miss when debugging: two objects print the same and still aren't equal.
value class: a struct with one field
A value class wraps exactly one value. On the JVM it needs @JvmInline, and the compiler usually replaces the wrapper with the underlying value, so there is no extra object allocation:
@JvmInline
value class UserId(val value: Long)
@JvmInline
value class Meters(val value: Double) {
operator fun plus(other: Meters) = Meters(value + other.value)
}
fun loadUser(id: UserId) = "user #${id.value}"
fun main() {
val id = UserId(42)
println(loadUser(id))
// loadUser(42) // does not compile: Long is not UserId
println(id)
println(id == UserId(42))
println(Meters(1.5) + Meters(2.0))
}
user #42
UserId(value=42)
true
Meters(value=3.5)
Value classes are a cheap way to give distinct types to values that would otherwise all be Long or String: IDs, units, validated strings. They have generated equals(), hashCode() and toString() like data classes, but no copy() or componentN(). See Values and references for how they are represented at runtime.
@JvmRecord: Java interop
A data class compiles to an ordinary JVM class. If Java code or a library expects a real java.lang.Record, annotate the data class with @JvmRecord. It requires JVM target 16 or later (for example kotlinc -jvm-target 17), and all properties must be val:
@JvmRecord
data class Money(val amount: Long, val currency: String)
fun main() {
val m = Money(1999, "EUR")
val cls = m.javaClass
println(cls.isRecord)
println(cls.superclass.name)
println(cls.recordComponents.joinToString { "${it.type.simpleName} ${it.name}" })
// Java-style record accessors exist alongside Kotlin properties
println(cls.getMethod("amount").invoke(m))
println(m.amount)
println(m)
}
true
java.lang.Record
long amount, String currency
1999
1999
Money(amount=1999, currency=EUR)
The class extends java.lang.Record, and Java code can call m.amount() and m.currency() as with any record. Kotlin code keeps using the properties. Use @JvmRecord when the class crosses into Java code that relies on records, for example for serialization or pattern matching; otherwise a plain data class is enough.
Summary
| Need | Kotlin |
|---|---|
| Struct / record with named fields | data class |
| Quick two- or three-value tuple | Pair (a to b), Triple |
| Return several values from a function | small data class, or Pair for obvious cases |
| Unpack a record or tuple | destructuring val (a, b) = x |
| One of several shapes | sealed interface + data class / data object |
| Type-safe wrapper around one value | @JvmInline value class |
| Real Java record | @JvmRecord data class |
- Only primary constructor properties take part in
equals(),hashCode(),toString()andcopy(). - Keep data class properties
val, and produce updated values withcopy(). - Positional destructuring breaks silently when properties are reordered; use it for small, stable types.
- Use
Listinstead of arrays inside data classes, or overrideequals()andhashCode().