Programming Search⌘K

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__)
Output
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

LanguageVerdictNote
PythonStandard library
C++Idiom
JavaNative
CAbsentC structs have no methods; a program writes its own functions to compare and print them, and == does not compile for structs.
C#Native
JavaScriptAbsent
TypeScriptAbsentAs 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.
GoIdiom
RustStandard library
KotlinNativeA 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.
SQLDoes not applySQL keeps data in rows of tables; there are no classes.
BashDoes not applyBash has no user types.
PowerShellIdiomA [pscustomobject] holds named values and prints them as a table, but it has no generated equality; a PowerShell class can also hold the data.
HTMLDoes not applyHTML has no user types.
CSSDoes not applyCSS has no user types.
Regular expressionsDoes not applyRegular 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() and hashCode() pair, a toString(), componentN() functions and copy().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, hashCode and toString "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=True or unsafe_hash=True.
  • C# records give "Value equality", "Concise syntax for nondestructive mutation" and "Built-in formatting for display".6 A record is a reference type and a record struct is 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
PythonGitHub
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))
Output
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. @dataclass writes __init__, __repr__ and __eq__ from the annotated fields; frozen=True adds a hash, and order=True adds < and the other order methods.
  • The methods compare the fields as a tuple in their order, so Version(1, 4) is before Version(1, 10).
  • field(compare=False) leaves note out 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';
}
Output
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== and operator<=> give equality and order from the members.
  • std::set uses <, so the struct can be a key without more code.
  • C++ generates no string form; the type needs its own operator<<.
JavaGitHub
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());
    }
}
Output
Version[major=1, minor=4]
true 4
true
[a.txt, b.txt]
  • Verdict: native. A record declares its components in the header, and the compiler writes the constructor, the accessors such as minor(), equals, hashCode and toString.
  • Equal records have equal hash codes, so a HashSet finds an equal copy.
  • A record is shallowly immutable: Release keeps the list that it was given, so a change to that list shows in the record. A compact constructor can store List.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);
Output
Version { Major = 1, Minor = 4 }
True
False
Version { Major = 1, Minor = 5 }
1
Point { X = 2, Y = 3 } 5
  • Verdict: native. A positional record gets init-only properties, a constructor, value equality with ==, GetHashCode, ToString and a Deconstruct method.
  • A record is a reference type, so ReferenceEquals tells the two objects apart, but == compares the values. A record struct is a value type.
  • with makes a copy with some properties changed; the original does not change.
JavaScriptGitHub
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);
Output
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 and toString by hand, and Object.freeze makes the fields read-only.
  • === compares references, so two equal versions are not ===.
  • Set and Map also compare keys by reference and cannot use equals, 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))
}
Output
{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, and fmt prints them with %v and %+v.
  • Assignment copies a struct, so b := a followed 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.
RustGitHub
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);
}
Output
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: Debug for the debug form, PartialEq and Eq for ==, Hash for hash sets and maps, and PartialOrd and Ord for < and sorting.
  • The derived order compares the fields in their order of declaration.
  • The struct update syntax ..a.clone() takes the other fields from a, so it makes a copy with changes.
  • Tuples with names. Python's namedtuple and typing.NamedTuple give 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#'s with, Scala's copy and Python's replace make 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 has init blocks.
  • Pattern matching. The fixed list of fields makes data classes good targets for destructuring and match: Kotlin's componentN, 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 to None: "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")
Output
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 equals symmetric 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 toString prints 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

  1. Data classes, Kotlin documentation, Introduction; Properties declared in the class body; Copying
  2. JEP 395: Records, Summary; Goals; History
  3. dataclasses, Data Classes, Python standard library, Module contents; replace
  4. Record (Java SE 21 & JDK 21), API documentation, Description
  5. PEP 557: Data Classes, Header; Abstract
  6. Records, C# reference, Introduction; Immutability; Built-in formatting for display
  7. Case Classes, Tour of Scala, Comparison; Copying
  8. Appendix C: Derivable Traits, The Rust Programming Language, Introduction; PartialEq and Eq; Hash
  9. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/Q32DVX/text.yaml