Kotlin value class vs data class
When implementing a value object with a single property in Kotlin, you may wonder whether to use an @JvmInline value class or a data class.
Both can express value equality. Their differences are most visible in their runtime representation and the language features available to them. This article focuses on Kotlin on the JVM.
- Comparison covers the differences and their reasons.
- Design and implementation describes when each type fits.
- A common misunderstanding explains what happens to type safety.
- Choosing between them summarizes the trade-offs.
For examples of value objects, see the Japanese implementation guide.
Comparison
Section titled “Comparison”| Aspect | @JvmInline value class | data class |
|---|---|---|
| Runtime representation | Often represented by its underlying type, such as UUID | Normally represented as an object |
| Equality | Compares the wrapped value | Compares primary-constructor properties |
| Properties | One underlying property | One or more primary-constructor properties |
toString | Can be overridden when a specific format is needed | Generated with the class and property names |
| Debugging | May appear as the underlying type | Often appears as the class type |
| Library integration | May require library-specific support or configuration | Often supported as an ordinary class |
Runtime representation
Section titled “Runtime representation”A value class is a distinct Kotlin type. On the JVM, the compiler can represent it using its underlying value, avoiding an extra wrapper in many cases.
import java.util.UUID
@JvmInlinevalue class UserId(val value: UUID)
fun findUser(id: UserId) { /* ... */ }The compiler still distinguishes UserId from UUID. A value class can also be boxed, for example when used as a nullable value, a generic type, or an interface. The actual representation depends on how it is used. Kotlin’s value class documentation
A data class is normally represented as an object.
data class UserId(val value: UUID)Avoided wrappers may reduce allocations in some workloads. The effect on memory and garbage collection depends on usage and should be measured in the application.
Equality
Section titled “Equality”A value object treats equal values as equal. For a value class, equality compares the wrapped value. For a data class, generated equals and hashCode use properties declared in the primary constructor. Properties declared only in the class body are excluded from those generated methods. Kotlin data classes
For a single-property value object the results can be similar. With a data class, generated equality also handles multiple primary-constructor properties.
Properties and validation
Section titled “Properties and validation”A value class has one underlying property, making it useful for wrapping a single value such as a UserId or Email.
@JvmInlinevalue class Email(val value: String) { init { require(value.contains("@")) { "Invalid email address" } }}This example checks only for an @ character. It is not a complete email address validator.
A data class can group multiple properties into one concept, such as money with an amount and currency. An init block can validate their values and relationships.
enum class Currency { JPY, USD}
data class Money( val amount: Long, val currency: Currency,) { init { require(amount >= 0) { "Amount must be non-negative" } }}Both types can use init. Consider whether the concept consists of one underlying value or a combination of attributes.
toString and debugging
Section titled “toString and debugging”A data class generates a toString such as UserId(value=550e8400-e29b-...), which includes the class and property names. A value class can also override toString. Its appearance in logs, debuggers, and libraries may vary with its representation and tooling.
A debugger may display a value class as its underlying UUID, while a data class is often easier to see as a UserId object. Check the tools and versions used by your project.
Library integration
Section titled “Library integration”Serialization libraries, ORMs, and other frameworks differ in their support for value classes. Depending on the library and its version, a value class may require configuration or a custom converter. A data class may be simpler to integrate in some projects. Check the relevant library’s documentation and test the representation required by your API or database.
Design and implementation
Section titled “Design and implementation”An @JvmInline value class is a candidate when you want to distinguish single-value identifiers such as UserId and OrderId, enforce a constraint around one value, or investigate allocation costs.
A data class is a candidate when a concept combines multiple properties, validation involves their relationship, or integration with tools that expect objects is a priority. Team familiarity and readability can also influence the choice.
A common misunderstanding
Section titled “A common misunderstanding”An underlying runtime representation does not make UserId interchangeable with UUID or OrderId in Kotlin source code. They remain distinct types at compile time.
import java.util.UUID
@JvmInlinevalue class UserId(val value: UUID) { companion object { fun generate(): UserId = UserId(UUID.randomUUID()) }}
@JvmInlinevalue class OrderId(val value: UUID) { companion object { fun of(value: UUID): OrderId = OrderId(value) }}
fun findUser(id: UserId) { /* ... */ }fun findOrder(id: OrderId) { /* ... */ }fun saveRaw(id: UUID) { /* ... */ }
val userId = UserId.generate()
findUser(userId) // OKfindOrder(userId) // Compile error: OrderId is requiredsaveRaw(userId) // Compile error: UUID is requiredsaveRaw(userId.value) // OK: explicitly unwrap the valueA data class also does not implicitly convert to its underlying property type.
Unwrapping with .value
Section titled “Unwrapping with .value”The compiler cannot prevent a different identifier type from being constructed after the underlying value is extracted.
val userId = UserId.generate()val orderId = OrderId.of(userId.value) // Compiles, but mixes up the meaningsTo reduce this risk, consider keeping unwrapping at boundaries such as database and serialization layers, making value private when practical, and accepting UserId or OrderId in domain functions instead of raw UUID values.
Choosing between them
Section titled “Choosing between them”| Situation | Starting point |
|---|---|
| Wrap a single identifier in a distinct type | Consider @JvmInline value class |
| Validate a combination of properties | Consider data class |
| Library integration is difficult | Check whether a data class is easier to support |
| Keep a consistent calling API | Either can expose a common factory interface |
Choose based on the value being modeled, the required tooling, and measured performance where relevant. A project may use both forms when their respective trade-offs suit different concepts.
For concrete single-property and multi-property examples, see the Japanese implementation guide.