Conceptcore
Data classes
Also called dataclass, data carrier class, case class, record class, record struct, data-only class, generated value methods.
A data class is a class made to hold a fixed set of values, for which the compiler generates the constructor, equality, the hash, the string form and often a copy method.
- Applies to
- core-languages
Idea
Many classes exist only to hold values: a point with x and y, a book with a title and a year, a message with a sender and a text. Such a class needs the same methods each time: a constructor that sets each field, equality that compares the fields, a hash that agrees with equality, a string form that shows the fields, and often a way to copy the object with one field changed. Written by hand, these methods are long, and each new field must be added to all of them.
A data class asks the compiler to write the methods from the list of fields. Kotlin: "For each data class, the compiler automatically generates additional member functions that allow you to print an instance to readable output, compare instances, copy instances, and more."1 Java's JEP 395 gives the same goal: "Automatically implement data-driven methods such as equals and accessors."2
A data class is a record type with methods. The record type is the idea of a value with named fields; the data class is the language feature that gives such a value the universal object methods for free.
How it works
The programmer lists the fields, and the compiler or a library generates the methods from that list. Python's @dataclass reads the annotated class variables and adds "generated special methods such as init() and repr()".3 With frozen=True, the fields cannot change, and the class also gets a hash:
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Book:
title: str
year: int
tags: tuple = ()
a = Book("Dune", 1965)
b = Book("Dune", 1965)
print(a)
print(a == b, a is b, hash(a) == hash(b))
c = replace(a, year=1966)
print(c)
try:
a.year = 2000
except AttributeError as e:
print(type(e).__name__)
Book(title='Dune', year=1965, tags=())
True False True
Book(title='Dune', year=1966, tags=())
FrozenInstanceError
a and b are two objects, but they are equal and have equal hashes, because the generated methods compare the fields. replace makes a new object with one field changed, so a frozen object is never changed in place.
The generated methods are the same in each language:
| Method | Python @dataclass |
Java record |
Kotlin data class |
C# record |
Rust #[derive] |
|---|---|---|---|---|---|
| constructor | __init__ |
canonical constructor | primary constructor | primary constructor | struct literal |
| equality | __eq__ |
equals |
equals |
Equals, == |
PartialEq, Eq |
| hash | __hash__ when frozen |
hashCode |
hashCode |
GetHashCode |
Hash |
| string form | __repr__ |
toString |
toString |
ToString |
Debug |
| copy with changes | replace |
none in Java 21 | copy |
with |
struct update syntax |
| order | order=True |
none | none | none | PartialOrd, Ord |
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Idiom | |
| Java | Native | |
| C | Absent | C structs have no methods; a program writes its own functions to compare and print them, and == does not compile for structs. |
| C# | Native | |
| JavaScript | Absent | |
| TypeScript | Absent | As JavaScript; a class or an interface describes the fields, but no equality, hash or string form is generated; no example file because it would repeat the JavaScript answer. |
| Go | Idiom | |
| Rust | Standard library | |
| Kotlin | Native | A data class gets equals, hashCode, toString, componentN functions and copy from the properties of its primary constructor; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | SQL keeps data in rows of tables; there are no classes. |
| Bash | Does not apply | Bash has no user types. |
| PowerShell | Idiom | A [pscustomobject] holds named values and prints them as a table, but it has no generated equality; a PowerShell class can also hold the data. |
| HTML | Does not apply | HTML has no user types. |
| CSS | Does not apply | CSS has no user types. |
| Regular expressions | Does not apply | Regular expressions have no user types. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | stdlib | @dataclass; also typing.NamedTuple |
| JavaScript | absent | no generated methods; plain objects and classes |
| TypeScript | absent | as JavaScript; type aliases and interfaces describe the shape only |
| Java | native | record classes |
| Kotlin | native | data class |
| C# | native | record, record class and record struct |
| Go | idiom | plain structs: == and %+v work on them without code |
| Rust | stdlib | #[derive(Debug, Clone, PartialEq, Eq, Hash)] on a struct |
| C | absent | plain structs without methods |
| C++ | idiom | aggregates with defaulted operator== and operator<=> |
| Bash | n/a | no user types |
| PowerShell | idiom | [pscustomobject] holds named values; no generated equality |
| SQL | n/a | rows of a table hold the data; no classes |
| Regex | n/a | no user types |
| HTML | n/a | no user types |
| CSS | n/a | no user types |
- Kotlin derives the methods "from all properties declared in the primary constructor": the
equals()andhashCode()pair, atoString(),componentN()functions andcopy().1 A property declared in the class body is not part of them. - Java records are "classes that act as transparent carriers for immutable data".2 The fields are final, and
equals,hashCodeandtoString"are derived from all of the component fields".4 "A record class is implicitly final, and cannot be abstract."2 - Python dataclasses are normal classes with generated methods. PEP 557 says that they "can be thought of as “mutable namedtuples with defaults”".5 A hash comes only with
frozen=Trueorunsafe_hash=True. - C# records give "Value equality", "Concise syntax for nondestructive mutation" and "Built-in formatting for display".6 A
recordis a reference type and arecord structis a value type. - Scala case classes are "good for modeling immutable data", and they are "compared by structure and not by reference".7
- Rust has no data class keyword.
#[derive]writes each trait from the fields: "When PartialEq is derived on structs, two instances are equal only if all fields are equal".8 - C++ lets a class ask for a generated comparison: "Comparison operator functions can be explicitly defaulted to request the compiler to generate the corresponding default comparison for a class."9
from dataclasses import dataclass, field, replace
@dataclass(frozen=True, order=True)
class Version:
major: int
minor: int
note: str = field(default="", compare=False)
def __post_init__(self):
if self.major < 0 or self.minor < 0:
raise ValueError("negative part")
a = Version(1, 4, "first")
b = Version(1, 10)
print(a)
print(a < b, a == Version(1, 4), len({a, Version(1, 4)}))
print(sorted([b, a])[0])
print(replace(b, minor=11))
Version(major=1, minor=4, note='first')
True True 1
Version(major=1, minor=4, note='first')
Version(major=1, minor=11, note='')
- Verdict: stdlib.
@dataclasswrites__init__,__repr__and__eq__from the annotated fields;frozen=Trueadds a hash, andorder=Trueadds<and the other order methods. - The methods compare the fields as a tuple in their order, so
Version(1, 4)is beforeVersion(1, 10). field(compare=False)leavesnoteout of equality, the hash and the order.__post_init__runs after the generated__init__to check the values.
#include <algorithm>
#include <compare>
#include <iostream>
#include <set>
#include <vector>
struct Version {
int major = 0;
int minor = 0;
friend bool operator==(const Version&, const Version&) = default;
friend auto operator<=>(const Version&, const Version&) = default;
};
std::ostream& operator<<(std::ostream& os, const Version& v) {
return os << "Version{" << v.major << ", " << v.minor << "}";
}
int main() {
Version a{.major = 1, .minor = 4};
Version b = a;
b.minor = 10;
std::cout << a << ' ' << b << '\n';
std::cout << std::boolalpha << (a == Version{1, 4}) << ' ' << (a < b) << '\n';
std::set<Version> seen{a, b, a};
std::cout << seen.size() << '\n';
std::vector<Version> all{b, a};
std::sort(all.begin(), all.end());
std::cout << all.front() << '\n';
}
Version{1, 4} Version{1, 10}
true true
2
Version{1, 4}
- Verdict: idiom. An aggregate struct gets construction from a brace list, here with designated initializers, and a member-wise copy. Defaulted
operator==andoperator<=>give equality and order from the members. std::setuses<, so the struct can be a key without more code.- C++ generates no string form; the type needs its own
operator<<.
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
record Version(int major, int minor) {
// A compact constructor checks the components.
Version {
if (major < 0 || minor < 0) {
throw new IllegalArgumentException("negative part");
}
}
}
record Release(String name, List<String> files) {}
public static void main(String[] args) {
Version a = new Version(1, 4);
System.out.println(a);
System.out.println(a.equals(new Version(1, 4)) + " " + a.minor());
Set<Version> seen = new HashSet<>(List.of(a));
System.out.println(seen.contains(new Version(1, 4)));
var files = new java.util.ArrayList<>(List.of("a.txt"));
Release r = new Release("r1", files);
files.add("b.txt");
System.out.println(r.files());
}
}
Version[major=1, minor=4]
true 4
true
[a.txt, b.txt]
- Verdict: native. A
recorddeclares its components in the header, and the compiler writes the constructor, the accessors such asminor(),equals,hashCodeandtoString. - Equal records have equal hash codes, so a
HashSetfinds an equal copy. - A record is shallowly immutable:
Releasekeeps the list that it was given, so a change to that list shows in the record. A compact constructor can storeList.copyOf(files)instead.
using System;
using System.Collections.Generic;
var a = new Version(1, 4);
Console.WriteLine(a);
Console.WriteLine(a == new Version(1, 4));
Console.WriteLine(ReferenceEquals(a, new Version(1, 4)));
var b = a with { Minor = 5 };
Console.WriteLine(b);
var seen = new HashSet<Version> { a, new Version(1, 4) };
Console.WriteLine(seen.Count);
var p = new Point(2, 3);
var (x, y) = p;
Console.WriteLine($"{p} {x + y}");
record Version(int Major, int Minor);
readonly record struct Point(int X, int Y);
Version { Major = 1, Minor = 4 }
True
False
Version { Major = 1, Minor = 5 }
1
Point { X = 2, Y = 3 } 5
- Verdict: native. A positional
recordgets init-only properties, a constructor, value equality with==,GetHashCode,ToStringand aDeconstructmethod. - A
recordis a reference type, soReferenceEqualstells the two objects apart, but==compares the values. Arecord structis a value type. withmakes a copy with some properties changed; the original does not change.
class Version {
constructor(major, minor) {
this.major = major;
this.minor = minor;
Object.freeze(this);
}
equals(other) {
return (
other instanceof Version &&
this.major === other.major &&
this.minor === other.minor
);
}
with(changes) {
const v = { ...this, ...changes };
return new Version(v.major, v.minor);
}
toString() {
return `Version(${this.major}, ${this.minor})`;
}
}
const a = new Version(1, 4);
console.log(`${a}`);
console.log(a === new Version(1, 4), a.equals(new Version(1, 4)));
console.log(`${a.with({ minor: 5 })}`);
console.log(new Set([a, new Version(1, 4)]).size);
Version(1, 4)
false true
Version(1, 5)
2
- Verdict: absent. JavaScript generates no methods from fields, so the class writes
equals, a copy method andtoStringby hand, andObject.freezemakes the fields read-only. ===compares references, so two equal versions are not===.SetandMapalso compare keys by reference and cannot useequals, so the set keeps both objects.
package main
import "fmt"
type Version struct {
Major int
Minor int
}
func main() {
a := Version{Major: 1, Minor: 4}
fmt.Printf("%v %+v\n", a, a)
fmt.Println(a == Version{1, 4})
b := a
b.Minor = 5
fmt.Println(a.Minor, b.Minor)
seen := map[Version]bool{a: true}
fmt.Println(seen[Version{1, 4}], len(seen))
}
{1 4} {Major:1 Minor:4}
true
4 5
true 1
- Verdict: idiom. Go has no data classes, but a plain struct already has most of their behavior:
==compares the fields, andfmtprints them with%vand%+v. - Assignment copies a struct, so
b := afollowed by a change is a copy with changes. - A struct with comparable fields can be a map key. A struct with a slice or a map field is not comparable, and
==does not compile for it.
use std::collections::HashSet;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct Version {
major: u32,
minor: u32,
}
fn main() {
let a = Version { major: 1, minor: 4 };
let b = Version { minor: 10, ..a.clone() };
println!("{:?}", a);
println!("{} {}", a == Version { major: 1, minor: 4 }, a < b);
let seen: HashSet<Version> = [a.clone(), b.clone(), a.clone()].into_iter().collect();
println!("{}", seen.len());
let mut all = vec![b, a];
all.sort();
println!("{:?}", all);
}
Version { major: 1, minor: 4 }
true true
2
[Version { major: 1, minor: 4 }, Version { major: 1, minor: 10 }]
- Verdict: stdlib.
#[derive]writes each listed trait from the fields:Debugfor the debug form,PartialEqandEqfor==,Hashfor hash sets and maps, andPartialOrdandOrdfor<and sorting. - The derived order compares the fields in their order of declaration.
- The struct update syntax
..a.clone()takes the other fields froma, so it makes a copy with changes.
Variations and related ideas
- Tuples with names. Python's
namedtupleandtyping.NamedTuplegive a tuple named fields, and JEP 395 says that "Records can be thought of as nominal tuples".2 A tuple is ordered and can be indexed; a data class has only names. - Copy with changes. Kotlin's
copy, C#'swith, Scala'scopyand Python'sreplacemake a new object with some fields changed. The copy is shallow: see object cloning. - Validation. A data class still has a constructor that can check its values. Java records have a compact constructor, Python dataclasses have
__post_init__, and Kotlin hasinitblocks. - Pattern matching. The fixed list of fields makes data classes good targets for destructuring and
match: Kotlin'scomponentN, Python's__match_args__, and Java's record patterns. - Immutability. Most data classes are immutable or can be made so: Java records, Scala case classes and frozen dataclasses. See immutability.
Pitfalls
- Equality without a hash. A mutable Python dataclass has
__eq__, but its hash is set toNone: "If eq is true and frozen is false, hash() will be set to None, marking it unhashable (which it is, since it is mutable)."3 Its objects cannot go in a set:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(1, 2)
print(p == Point(1, 2))
try:
seen = {p}
except TypeError:
print("TypeError: Point is unhashable")
True
TypeError: Point is unhashable
Use frozen=True for values that go in sets or are dictionary keys.
- Shallow immutability. A Java record is "a shallowly immutable, transparent carrier for a fixed set of values".4 A record that holds a list can still have the list changed. C# says the same of its records: "the data that a reference-type property refers to can be changed".6 Copy mutable inputs in the constructor, or store immutable collections.
- Fields left out of equality. A Kotlin property declared in the class body is not in
equals, so two objects that differ in it are equal.1 Put every field that matters in the primary constructor. - Equality and inheritance. Generated equality compares the fields of one class. A subclass that adds a field cannot keep
equalssymmetric with its parent. Java records are final,2 and Kotlin data classes "can't be abstract, open, sealed, or inner",1 so no subclass can add a field to them. See implement equality for a type. - Secrets in the string form. The generated
toStringprints every field, including a password or a token. Override it for such types.
Cost
A data class costs the same as a hand-written class with the same methods. The generated equality and hash read every field, so their cost grows with the number and the size of the fields; a data class with a large list field compares and hashes the whole list. A copy with changes allocates a new object each time, which matters only in hot loops.
History
Scala has case classes and Kotlin has data classes. Python got dataclasses from PEP 557, created on June 2, 2017, for Python 3.7.5 Java records were a preview in JDK 14 and JDK 15, and JEP 395 made them final in JDK 16.2 C# added records, and Rust has derived the same methods from struct fields with #[derive].
References
- Data classes, Kotlin documentation, Introduction; Properties declared in the class body; Copying
- JEP 395: Records, Summary; Goals; History
- dataclasses, Data Classes, Python standard library, Module contents; replace
- Record (Java SE 21 & JDK 21), API documentation, Description
- PEP 557: Data Classes, Header; Abstract
- Records, C# reference, Introduction; Immutability; Built-in formatting for display
- Case Classes, Tour of Scala, Comparison; Copying
- Appendix C: Derivable Traits, The Rust Programming Language, Introduction; PartialEq and Eq; Hash
- Default comparisons, cppreference.com, Introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag Q32DVX Edit this page History Report an error Markdown