Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 134 ยท Classes and Objects

Value Classes

Learn Kotlin value classes: wrap an Int or String in a distinct type with no runtime cost, validate in init, know the restrictions, boxing rules and when to choose them.

Look at this function signature: fun ship(orderId: Int, customerId: Int). Both parameters are plain integers, so nothing stops you from passing them in the wrong order. The program compiles, runs, and quietly ships order 42 to customer 1001. Bugs like this are called primitive obsession: using a bare Int, String or Double for something that has a meaning of its own (an id, an email address, a distance in meters).

The cure is a small wrapper type per meaning. The cost, in most languages, is an extra object for every value. Kotlin's value class gives you the wrapper without the cost: the compiler checks your types, and at run time it usually replaces the wrapper with the raw value it holds. This lesson shows how to declare one, how to add validation and behavior, the rules you must follow, when a real object is created after all (boxing), and when a data class or a plain type alias is the better choice.

The problem: everything is an Int

Kotlin Arguments in the wrong order compile fine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output says "Shipping order 42 to customer 1001", which is wrong and silent. A type alias does not help: typealias OrderId = Int only gives Int a second name, so an OrderId and a CustomerId are still the same type and still interchangeable.

Declaring a value class

A value class has the value modifier, the @JvmInline annotation (on the JVM, which is where our code runs), and exactly one property in its primary constructor, declared with val:

Kotlin OrderId and CustomerId as distinct types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You still write OrderId(1001) like a normal constructor call, but there is no new object in the compiled code of ship. The JVM sees an int. The printed form OrderId(value=7) comes from a generated toString, just as in a data class. Now try the mix-up again:

Kotlin The compiler catches swapped ids (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler rejects both arguments: error: argument type mismatch: actual type is 'CustomerId', but 'OrderId' was expected. and the mirror-image message for the second argument. The check costs nothing at run time and turns a silent data bug into a compile error.

On the JVM, always write @JvmInline on a value class; it tells the compiler to represent the class by its wrapped value. The older word inline class was the first name of this feature and is now deprecated; use value class.

Equality, hashing and printing come for free

A value class has no identity: two values are equal exactly when their wrapped values are equal. The compiler generates equals, hashCode and toString from the single property, so value classes work as map keys and set elements without extra code:

Kotlin Value equality and use as a map key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Referential equality does not exist for value classes, because there may be no object to compare. Writing a === b is a compile error. If you need identity, you need a normal class.

Validation in init and extra members

A value class may have an init block, secondary constructors, computed properties and functions. It may implement interfaces. It may not have a property with a backing field other than the one in the constructor, because that would make the value bigger than one field. The most useful pattern is a value class that checks its input once, at construction, so every Email in the program is known to be valid:

Kotlin A validated Email type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

sendWelcome can now trust its parameter: if it received an Email, the check already passed. Compare that with taking a String and validating (or forgetting to) in every function. This idea, "make illegal states unrepresentable", comes back in Encapsulation and Design. For error handling with require, see require, check and assert.

Units of measure and operators

Another classic use is to stop mixing units. A Meters value and a Feet value both wrap a Double, yet adding them directly should not compile:

Kotlin Meters and Feet cannot be mixed by accident

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The conversion is explicit (toMeters()), so the unit change is visible in the code. The Kotlin standard library itself uses this technique: kotlin.time.Duration is a value class wrapping a Long, which is why 5.seconds + 300.milliseconds creates no objects in a hot loop. Result and unsigned numbers such as UInt are value classes too.

The rules and restrictions

A value class is a compile-time illusion, so the compiler keeps it simple. The main restrictions are:

  • Exactly one val property in the primary constructor (not var, not zero, not two).
  • No other properties with backing fields. Computed properties without a field are fine.
  • No open, abstract, sealed or inner modifiers, and it cannot extend a class (it can implement interfaces).
  • It cannot be used with ===.
Kotlin Two properties are not allowed (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler answers error: value class must have exactly one primary constructor parameter. If you need two or more values, use a data class. A related mistake is adding a field to the body:

Kotlin No extra backing fields (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The error is error: value class cannot have properties with backing fields. Write val doubled: Int get() = value * 2 instead; with no backing field it is just a function in disguise.

Boxing: when an object appears anyway

The compiler stores the raw value only where the static type is exactly the value class. As soon as the value has to travel in a place that expects a general object, the compiler boxes it, creating a real wrapper instance. This happens when you use a value class:

  • as a nullable type (OrderId?), unless the underlying type is itself a non-null reference type such as String;
  • as a type argument, so List<OrderId> stores boxed objects, while IntArray would not;
  • through a supertype such as Any, Comparable<Meters> or any interface it implements;
  • in a Pair, a lambda parameter of a generic function type, and so on.
Kotlin Boxing is invisible but real

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Boxing is not a bug; it is the price of the abstraction at those boundaries, and it is the same price a normal class pays always. The practical advice: use value classes in hot paths with direct parameters and fields, and do not worry about them in a List of a few hundred entries. If profiling shows heavy boxing in a tight loop over a collection, a primitive array (IntArray) of the underlying values may be the answer.

Name mangling and the Java view

Because OrderId and Int both become int in bytecode, fun ship(id: OrderId) and fun ship(id: Int) would clash. The compiler solves this by mangling the function name (it adds a hash suffix such as ship-ab12cd3). Kotlin callers never see the mangled name, but Java code does, and a function taking a value class is hard to call from Java. If a function must be callable from Java with a stable name, either accept the raw type at the boundary or use a normal class there. See Java Interoperability for more.

Value class, data class or typealias?

You need Choose
A distinct type around exactly one value, no run-time overhead @JvmInline value class
Several values that belong together data class
Only a shorter or clearer name, no new type typealias
Identity, mutable state, inheritance an ordinary class

A value class is also not a replacement for validation across several fields (for example "start date before end date"). That belongs in a data class or a function that returns a sealed result.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main benefit of @JvmInline value class UserId(val value: Int) over typealias UserId = Int?

    A typealias is only another name for the same type. A value class creates a distinct type that the compiler checks, while the JVM usually sees the raw Int.
  2. 2. Which declaration is a valid value class on the JVM?

    A value class needs @JvmInline, exactly one read-only (val) constructor property, and cannot be open. The other declarations break one of these rules.
  3. 3. In which situation is a value class instance boxed into a real object?

    Generic type arguments such as the element type of a List need an object, so the compiler boxes. Direct parameters of the value class type, property reads and == work on the raw value.
  4. 4. What happens with val a = UserId(1); val b = UserId(1); println(a === b)?

    Value classes have no identity, so referential equality with === is rejected by the compiler. Use == to compare the wrapped values.
  5. 5. Where is the best place to check that an email string is well formed?

    An init block with require runs every time an Email is created, so any Email value in the program is known to be valid.

Summary

  • A value class wraps exactly one val property in a distinct type; on the JVM write @JvmInline value class Name(val value: T).
  • It prevents mix-ups of ids, units and validated strings at compile time, usually without allocating an object.
  • equals, hashCode and toString are generated from the wrapped value; === is not allowed.
  • You can add init validation, computed properties, functions, operators and interfaces, but no extra fields, no inheritance, no open.
  • The value is boxed when used as a nullable, a generic type argument or through a supertype such as Any or an interface.
  • Functions that take value classes get mangled names, which matters for Java callers.
  • Use a data class for several values, a typealias for a mere alias, and a normal class for identity.

Next: Delegation