Value classes

suggest change

A value class wraps exactly one value and gives it its own type. A UserId and an OrderId can both be a Long at runtime, but the compiler won't let you pass one where the other is expected:

@JvmInline
value class UserId(val raw: Long)

In most places the compiler removes the wrapper and uses the underlying long directly, so you get type safety without allocating an object. In some places the value has to be boxed into a real UserId object. Knowing where that happens is most of what you need to use value classes well.

Value classes are stable since Kotlin 1.5. They replaced the older experimental inline class syntax. Generic underlying types were added in Kotlin 1.7.20, and secondary constructors with bodies in Kotlin 1.9. @JvmExposeBoxed was added in Kotlin 2.2 and is still experimental. All examples here were compiled and run with Kotlin 2.4.21 on JDK 25.

Structs, tuples, and records has a short introduction that compares value classes with data classes. This article goes deeper.

Declaring a value class

On the JVM a value class needs the @JvmInline annotation and exactly one val in its primary constructor. Apart from that it can have most things a normal class has: methods, computed properties, operators, secondary constructors, a companion object, and interfaces:

@JvmInline
value class Cents(val amount: Long) : Comparable<Cents> {
    // secondary constructor with a body (allowed since Kotlin 1.9)
    constructor(euros: Int, cents: Int) : this(euros * 100L + cents) {
        println("built from $euros euros and $cents cents")
    }

    // computed property: no backing field
    val euros: Long get() = amount / 100

    operator fun plus(other: Cents) = Cents(amount + other.amount)
    operator fun times(n: Int) = Cents(amount * n)
    override fun compareTo(other: Cents) = amount.compareTo(other.amount)
    override fun toString() = "%d.%02d EUR".format(amount / 100, amount % 100)

    companion object {
        val ZERO = Cents(0)
    }
}

fun total(prices: List<Cents>): Cents = prices.fold(Cents.ZERO) { acc, p -> acc + p }

fun main() {
    val coffee = Cents(3, 50)
    val cake = Cents(425)
    println(coffee + cake * 2)
    println(coffee.euros)
    println(coffee < cake)
    println(total(listOf(coffee, cake)))
    println(Cents(350) == coffee)
    // val wrong: Cents = 350          // type mismatch: Int is not Cents
}
built from 3 euros and 50 cents
12.00 EUR
3
true
7.75 EUR
true

Value classes get equals(), hashCode() and toString() generated from the wrapped value. Unlike data classes they have no copy() or componentN(): there is only one field, so there is nothing to copy or destructure.

What is not allowed

A value class is a thin wrapper, and the compiler enforces that. Each of these lines is a compile error:

@JvmInline
value class P(val x: Int, val y: Int)

@JvmInline
value class Q(var x: Int)

@JvmInline
value class R(val x: Int) {
    var cache: Int = 0
    lateinit var s: String
}

open class Base
@JvmInline
value class S(val x: Int) : Base()

@JvmInline
value class U(val x: Int)

fun main() {
    val a = U(1); val b = U(1)
    println(a === b)
}
rules.kt:2:14: error: value class must have exactly one primary constructor parameter.
rules.kt:5:15: error: value class primary constructor must only have final read-only ('val') property parameters.
rules.kt:9:5: error: value class cannot have properties with backing fields.
rules.kt:10:14: error: value class cannot have properties with backing fields.
rules.kt:15:29: error: value class cannot extend classes.
rules.kt:22:13: error: identity equality for arguments of types 'U' and 'U' is prohibited.

The rules in short:

Validation in init

The best use of a value class is a type that can only hold valid values. Put the checks in an init block. It runs every time the value is created from Kotlin code, including when a value is created from JSON (see below):

@JvmInline
value class Email(val value: String) {
    init {
        require('@' in value && !value.startsWith('@') && !value.endsWith('@')) {
            "invalid email: '$value'"
        }
    }

    val domain: String get() = value.substringAfter('@')
}

@JvmInline
value class Port private constructor(val number: Int) {
    companion object {
        fun of(n: Int): Port? = if (n in 1..65535) Port(n) else null
        fun parse(s: String): Result<Port> = runCatching {
            val n = s.trim().toInt()
            of(n) ?: throw IllegalArgumentException("port out of range: $n")
        }
    }
}

fun main() {
    println(Email("ann@example.com").domain)
    try {
        Email("not-an-email")
    } catch (e: IllegalArgumentException) {
        println("error: ${e.message}")
    }

    println(Port.of(8443))
    println(Port.of(70000))
    // Port(80)    // error: cannot access 'constructor(number: Int): Port': it is private in 'Port'.
    for (s in listOf("443", "0", "http")) {
        println("$s -> ${Port.parse(s)}")
    }
}
example.com
error: invalid email: 'not-an-email'
Port(number=8443)
null
443 -> Success(Port(number=443))
0 -> Failure(java.lang.IllegalArgumentException: port out of range: 0)
http -> Failure(java.lang.NumberFormatException: For input string: "http")

Email throws on bad input, which suits values that should never be invalid, like configuration. Port has a private constructor and factory functions that return null or a Result, which suits user input. Once a function takes an Email parameter, it doesn't need to check the value again. The same pattern is used for the Secret type in Application security and the Email type in Immutability.

The guarantee has one hole: Java code calls functions with the raw underlying value and skips init. See the Java section below.

When a value class is boxed

The compiler uses the underlying type (here long) whenever it statically knows it has a UserId. When the value is used as something more general, it has to be wrapped in a real UserId object. javap shows what each function signature compiles to:

interface Labeled { val label: String }

@JvmInline
value class UserId(val raw: Long) : Labeled {
    override val label get() = "user-$raw"
}

@JvmInline
value class Name(val raw: String)

fun asIs(id: UserId) = id                // long
fun nullable(id: UserId?) = id           // boxed UserId
fun nullableName(n: Name?) = n           // String, null stays null
fun <T> generic(x: T) = x                // boxed
fun asInterface(x: Labeled) = x.label    // boxed
fun asAny(x: Any) = x                    // boxed
fun inList(ids: List<UserId>) = ids.size // each element boxed

fun main() {
    val id = UserId(7)
    val a: Any = id
    println(a.javaClass.name)
    println(asInterface(id))
    println(generic(id) == id)

    val boxed1: Any = id
    val boxed2: Any = id
    println(boxed1 === boxed2)   // two separate boxes
    println(boxed1 == boxed2)
}
UserId
user-7
true
false
true
$ javap -cp out BoxingKt
public final class BoxingKt {
  public static final long asIs-Bu7z9Ig(long);
  public static final UserId nullable-EbZ85Aw(UserId);
  public static final java.lang.String nullableName-SnuFtEM(java.lang.String);
  public static final <T> T generic(T);
  public static final java.lang.String asInterface(Labeled);
  public static final java.lang.Object asAny(java.lang.Object);
  public static final int inList(java.util.List<UserId>);
  ...
}

A value is boxed when it is used as:

In main, javap -c shows a call to UserId.box-impl before each of asInterface, generic and the two Any assignments, and unbox-impl after generic returns. Each box is a new object, which is why boxed1 === boxed2 is false and why === is banned on the value class type itself.

When the variable has the value class type, calls stay unboxed even for interface members: id.label compiles to a static call UserId.getLabel-impl(long).

Generic underlying types and delegation

Since Kotlin 1.7.20 the wrapped value can have a generic type. A value class can also implement an interface by delegating to the wrapped value with by, which gives you a restricted type that still has the full API:

@JvmInline
value class NonEmptyList<T>(val items: List<T>) : List<T> by items {
    init { require(items.isNotEmpty()) { "list must not be empty" } }

    val head: T get() = items.first()
}

@JvmInline
value class Slug(private val s: String) : CharSequence by s {
    init { require(s.all { it.isLowerCase() || it.isDigit() || it == '-' }) { "bad slug: $s" } }
    override fun toString() = s
}

fun <T> nonEmptyOf(first: T, vararg rest: T) = NonEmptyList(listOf(first) + rest)

fun main() {
    val tags = nonEmptyOf("kotlin", "jvm", "value-class")
    println(tags.head)
    println(tags.size)
    println(tags.map { it.uppercase() })   // all List methods are available
    println(runCatching { NonEmptyList(emptyList<Int>()) }.exceptionOrNull()?.message)

    val slug = Slug("value-classes-101")
    println(slug.length)
    println(slug.startsWith("value"))      // CharSequence extension
    println("/articles/$slug")
}
kotlin
3
[KOTLIN, JVM, VALUE-CLASS]
list must not be empty
17
true
/articles/value-classes-101

nonEmptyOf compiles to a function that returns a plain java.util.List. When the type parameter is the wrapped value itself, as in value class Tagged<T : Number>(val value: T), the JVM representation is the upper bound of T. A function sum(a: Tagged<Int>, b: Tagged<Int>) compiles to sum-oaUz3xY(Number, Number).

Value classes are not allowed as vararg parameters (fun total(vararg ms: Meters) gives "prohibited vararg parameter type 'Meters'"). Take a List<Meters> instead.

Name mangling and calling from Java

asIs-Bu7z9Ig in the javap output above is a mangled name. Any function that takes a value class parameter gets a hash suffix. Without it, fun find(id: UserId) and fun find(id: Long) would both compile to find(long) and clash. Member functions and property getters that return a value class are mangled too.

The - makes these names impossible to call from Java. Use @JvmName to give a function a Java-friendly name:

@JvmInline
value class UserId(val raw: Long)

class Users {
    fun find(id: UserId): String = "user #${id.raw}"
    fun find(id: Long): String = "legacy #$id"   // no clash: the other one is mangled

    @JvmName("findById")
    fun lookup(id: UserId): String = "user #${id.raw}"

    fun current(): UserId = UserId(1)
    @get:JvmName("adminId")
    val admin: UserId get() = UserId(0)
}
$ javap -cp out Users
public final class Users {
  public Users();
  public final java.lang.String find-Bu7z9Ig(long);
  public final java.lang.String find(long);
  public final java.lang.String findById(long);
  public final long current-w0BlNpU();
  public final long adminId();
}
public class Main {
    public static void main(String[] args) {
        Users users = new Users();
        System.out.println(users.find(42L));      // the Long overload
        System.out.println(users.findById(42L));  // the UserId one, via @JvmName
        long admin = users.adminId();             // returns the raw long
        System.out.println(admin);
    }
}
legacy #42
user #42
0

Java sees findById(long). It can pass any long, and no init block runs, so a Java caller can create values your validation would reject. The constructor of UserId is private on the JVM, so Java can't create a UserId object either. current() has no @JvmName and stays uncallable from Java.

@JvmExposeBoxed (experimental)

@JvmName gives Java the raw long. Kotlin 2.2 added @JvmExposeBoxed, which instead generates extra, unmangled JVM methods that take and return the boxed OrderId. It also makes the OrderId constructor public, and that constructor runs init. It is still experimental in 2.4, so you must opt in with ExperimentalStdlibApi:

@file:OptIn(ExperimentalStdlibApi::class)

@JvmInline
@JvmExposeBoxed
value class OrderId(val raw: Long) {
    init { require(raw > 0) { "order id must be positive: $raw" } }
}

class Orders {
    @JvmExposeBoxed
    fun status(id: OrderId): String = "order ${id.raw}: shipped"

    @JvmExposeBoxed
    fun latest(): OrderId = OrderId(99)
}
$ javap -cp out Orders
public final class Orders {
  public Orders();
  public final java.lang.String status-W7xRUzs(long);
  public final java.lang.String status(OrderId);
  public final long latest-nIqnXBc();
  public final OrderId latest();
}

Kotlin keeps calling the mangled, unboxed versions. Java now has a normal API:

public class Main {
    public static void main(String[] args) {
        Orders orders = new Orders();
        OrderId id = new OrderId(42);
        System.out.println(orders.status(id));
        System.out.println(orders.latest());
        System.out.println(id.getRaw());
        try {
            new OrderId(-1);
        } catch (IllegalArgumentException e) {
            System.out.println("error: " + e.getMessage());
        }
    }
}
order 42: shipped
OrderId(raw=99)
42
error: order id must be positive: -1

Where to put the annotation:

Without the opt-in every use is an error:

NoOptIn.kt:3:2: error: this declaration needs opt-in. Its usage must be marked with '@kotlin.ExperimentalStdlibApi' or '@OptIn(kotlin.ExperimentalStdlibApi::class)'
@JvmExposeBoxed
 ^^^^^^^^^^^^^^

Use it in libraries that Java code calls. In a pure Kotlin codebase you don't need it.

Serialization

kotlinx.serialization writes a @Serializable value class as its underlying value, without wrapping it in an object. The init block runs during decoding, so invalid JSON fails before it reaches your code. Value classes with a primitive or String underlying type also work as map keys:

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

@Serializable
@JvmInline
value class Sku(val code: String) {
    init { require(code.matches(Regex("[A-Z]{3}-[0-9]{4}"))) { "bad SKU: $code" } }
}

@Serializable
@JvmInline
value class Quantity(val n: Int)

@Serializable
data class Order(val items: Map<Sku, Quantity>, val gift: Sku? = null)

fun main() {
    val order = Order(mapOf(Sku("ABC-0001") to Quantity(2), Sku("XYZ-0042") to Quantity(1)))
    val json = Json.encodeToString(order)
    println(json)
    println(Json.decodeFromString<Order>(json) == order)

    try {
        Json.decodeFromString<Order>("""{"items":{"abc":3}}""")
    } catch (e: IllegalArgumentException) {
        println("${e::class.simpleName}: ${e.message}")
    }
}
{"items":{"ABC-0001":2,"XYZ-0042":1}}
true
IllegalArgumentException: bad SKU: abc

This was compiled with the kotlinx.serialization compiler plugin and kotlinx-serialization-json 1.11.0. JSON and Object serialization cover the library in detail. Jackson supports value classes only through jackson-module-kotlin, and with limits. Some reflection-based libraries and mocking frameworks see the mangled names and the underlying type instead of your class. Check yours before you use value classes in DTOs.

Performance pitfalls

Boxing costs an allocation, and it's easy to cause without noticing. This program counts the bytes allocated by the current thread while it builds and sums a million values:

import java.lang.management.ManagementFactory

@JvmInline
value class Meters(val v: Double)

val mx = ManagementFactory.getThreadMXBean() as com.sun.management.ThreadMXBean
fun allocated() = mx.getThreadAllocatedBytes(Thread.currentThread().threadId())

fun measure(name: String, block: () -> Double) {
    val before = allocated()
    val result = block()
    val mb = (allocated() - before) / 1_000_000
    println("%-22s result=%.0f allocated=%d MB".format(name, result, mb))
}

const val N = 1_000_000

fun main() {
    measure("DoubleArray") {
        val a = DoubleArray(N) { it.toDouble() }
        var s = 0.0; for (x in a) s += x; s
    }
    measure("Array<Meters>") {
        val a = Array(N) { Meters(it.toDouble()) }
        var s = 0.0; for (m in a) s += m.v; s
    }
    measure("List<Meters>") {
        val a = List(N) { Meters(it.toDouble()) }
        var s = 0.0; for (m in a) s += m.v; s
    }
}
DoubleArray            result=499999500000 allocated=8 MB
Array<Meters>          result=499999500000 allocated=28 MB
List<Meters>           result=499999500000 allocated=28 MB

A DoubleArray stores 8 bytes per value. Array<Meters> and List<Meters> store a reference to a separate 24-byte box for every element, so they use 3.5 times as much memory, and reading them means following pointers. A value class doesn't get its own primitive array type. If you need one, wrap the primitive array instead: value class MetersArray(val raw: DoubleArray) with get/set operators. The standard library does this for unsigned types: UIntArray wraps an IntArray.

Other things to watch for:

Even when values are boxed, you keep the type safety, so value classes are still worth using. Boxing only matters when you're optimizing for allocations.

Value classes in the standard library

Several standard library types are value classes. UInt, ULong, UByte and UShort wrap the signed primitives. kotlin.time.Duration wraps a Long, and Result<T> wraps an Any?. A function that returns Duration returns a long on the JVM, and a Duration? or a List<Duration> holds boxes, just like your own value classes.

Value class, type alias or data class?

typealias UserId = Long value class UserId(val raw: Long) data class UserId(val raw: Long)
New type, checked by the compiler no yes yes
Runtime cost none none when unboxed always an object
Validation in init no yes yes
Number of fields n/a exactly one any
copy(), destructuring n/a no yes
Nice to call from Java yes needs @JvmName or @JvmExposeBoxed yes

A type alias is only another name: UserId and Long stay interchangeable, so it gives you no protection against mixing up IDs. Use a value class for IDs, units, money, and validated strings such as emails and slugs. Use a data class when you need more than one field, or when the type is mostly used from Java or in generic collections and would be boxed anyway.

Feedback about page:

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



Table Of Contents