Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Value Classes

Kotlin Value Classes

Value classes let developers wrap primitive types in a semantically meaningful type shell with almost no runtime overhead.

It solves problems like "using String for email and Int for user ID makes it easy to pass the wrong argument", without allocating an object on every use like a regular wrapper class.


What is a value class

The core idea of a value class is: at the source level it is a distinct type, but after compilation it degrades as much as possible to the underlying value it wraps.

First, let's look at a mistake that is easy to make without value classes.

Example

// All three parameters are String, so the compiler cannot prevent the caller from reversing the order

fun transfer

(

fromAccount

:

String

, toAccount

:

String

, amount

:

Double

)

{

    println

(

"Transfer $amount from $fromAccount to $toAccount"

)

}

fun main

(

)

{

    val account

=

"6222021234567890"

    val password

=

"runoob-2026"

   

// The parameter order is reversed, but it still compiles; the problem only shows up at runtime

    transfer

(

password, account,

100.0

)

}

Running result:



从 runoob-2026 转账 100.0 到 6222021234567890

If the account and password are each wrapped in two different value classes, the compiler can catch such errors at compile time.


From inline class to value class

The concept of a value class first appeared under the name inline class and has been available since Kotlin 1.3.

Since Kotlin 1.5, the official term is uniformly value class, and the @JvmInline annotation is required.

Version Syntax Description
Since Kotlin 1.3 inline class UserId(val value: Int) Use inline modifier, no annotation required
Since Kotlin 1.5 @JvmInline value class UserId(val value: Int) Officially recommended form; the old form is deprecated

Note:Writing this again under Kotlin 2.2 inline class will produce a deprecation warning; always use @JvmInline value class。

@JvmInline from the default imports kotlin.jvm package, so no extra import is needed.


Define and use a value class

A value class is declared with the two keywords @JvmInline and value.

The primary constructor must have exactly one parameter modified with val the modifier; this parameter is called the underlying property and is the data the value class actually stores.

Example

@JvmInline

value

class

UserId

(

val value

:

Int

)

@JvmInline

value

class

Email

(

val address

:

String

)

// The two parameters have different types, so reversing the order at the call site is a compile error

fun sendMail

(

to

:

Email, userId

:

UserId

)

{

    println

(

"Send email to user ${userId.value} at ${to.address}"

)

}

fun main

(

)

{

    val email

=

Email

(

"runoob@www.runoob.com"

)

    val id

=

UserId

(

1001

)

    sendMail

(

email, id

)

   

// Value classes automatically generate equals / hashCode / toString

    println

(

id

==

UserId

(

1001

)

)

    println

(

UserId

(

1001

)

==

UserId

(

1002

)

)

    println

(

id

)

}

Running result:



向 runoob@www.runoob.com 的用户 1001 发送邮件

true

false

UserId(value=1001)

Notice the last line of output: the toString automatically generated by the value class toString() has the format "ClassName(propertyName=value)", the same as a data class.


Validate values in an init block

A value class can have an init init block, supported since Kotlin 1.4.30.

This is suitable for rejecting illegal underlying values at construction time, taking "correct type" one step further to "correct value".

Example

@JvmInline

value

class

Percentage

(

val value

:

Int

)

{

    init

{

       

// Validate at construction; illegal values cannot be created at all

        require

(

value in

0

..

100

)

{

"Percentage must be between 0 and 100, currently $value"

}

   

}

}

fun main

(

)

{

    val progress

=

Percentage

(

80

)

    println

(

"Progress: ${progress.value}%"

)

   

// Use runCatching to capture construction exceptions for easier error display

    val result

=

runCatching

{

Percentage

(

120

)

}

    println

(

result.

exceptionOrNull

(

)

?

.

message

)

}

Running result:



进度:80%

百分比必须在 0 到 100 之间,当前为 120

If you want to force all construction through validation, make the primary constructor private and provide a factory function via a companion object.

Example

@JvmInline

value

class

Email

private

constructor

(

val address

:

String

)

{

    companion object

{

       

// Factory function: handles cleaning and validation uniformly; outsiders cannot bypass it

        fun of

(

raw

:

String

)

:

Email

{

            val normalized

=

raw.

trim

(

)

.

lowercase

(

)

            require

(

normalized.

contains

(

"@"

)

)

{

"Invalid email format: $raw"

}

           

return

Email

(

normalized

)

       

}

   

}

}

fun main

(

)

{

    val email

=

Email.

of

(

"  RUNOOB@www.Runoob.com  "

)

    println

(

email.

address

)

    val bad

=

runCatching

{

Email.

of

(

"runoob.com"

)

}

    println

(

bad.

exceptionOrNull

(

)

?

.

message

)

}

Running result:



runoob@www.runoob.com

邮箱格式不正确:runoob.com


Difference from data classes

Both value classes and data classes wrap data, but their design goals are completely different.

A data class focuses on "what this set of data is", while a value class focuses on "what this single value means".

Comparison Item Value class (value class) Data class (data class)
Number of properties Primary constructor has exactly one val property Primary constructor has at least one property, possibly several
Runtime representation Degrades as much as possible to the underlying value; usually no object is allocated Always a regular object
Auto-generated members equals / hashCode / toString equals / hashCode / toString / copy / componentN
Destructuring declarations Not supported Supported, destructured by property order
inheritance Cannot inherit from classes, but can implement interfaces Cannot be open / abstract / sealed, but can implement interfaces
Typical use Type-safe IDs, units, amounts, percentages DTOs, function return values, multi-field aggregates

Note:A value class cannot be marked with the data modifier, nor can it be open、abstract or sealed。


Limitations of value classes

The "zero overhead" of a value class comes from the compiler being able to use the underlying value directly, so the language must restrict its shape.

Limitation Description
The primary constructor has only one val parameter One more parameter would make the underlying value indeterminate
The underlying property can only be val Value classes are passed by value; modifying the underlying data is not allowed
Cannot have properties with a backing field Only computed properties are allowed (custom getters that store no data)
Cannot be an inner class An inner class must hold a reference to the outer class, which conflicts with value semantics
Cannot inherit from other classes but can implement interfaces
Must be final Cannot be open / abstract / sealed
@JvmInline is required on the JVM platform Not needed on other backends (such as Kotlin/Native)

It can have computed properties, as long as they do not store extra state.

Example

@JvmInline

value

class

Temperature

(

val celsius

:

Double

)

{

   

// Computed property: uses no extra memory; the getter computes it each time

    val fahrenheit

:

Double

        get

(

)

=

celsius

9

/

5

32

}

fun main

(

)

{

    val t

=

Temperature

(

25.0

)

    println

(

"${t.celsius} degrees Celsius"

)

    println

(

"${t.fahrenheit} degrees Fahrenheit"

)

}

Running result:



摄氏 25.0 度

华氏 77.0 度


When boxing and unboxing occur

The premise of a value class having "no extra overhead" is that the compiler can represent it directly with the underlying type.

When value classes are boxed and unboxed: when used directly as the UserId type or as a function parameter or return value, no boxing occurs and it is just an Int at runtime; when used as a nullable type, a generic parameter, an interface, or a collection element, it is boxed into an object

Once a value class needs to be used as a regular object reference, the compiler boxes it automatically, and at that point it is no different from a regular wrapper class.

Usage Whether it is boxed Reason
Used directly as a variable, parameter, or return value of the concrete type Not boxed The underlying type is used directly after compilation
Assigned to Any or to an interface it implements Boxed Requires an object header and a virtual method table
Nullable type UserId? Boxed The underlying Int cannot represent null
As a generic type argument, such as List Boxed Generic type parameters only accept reference types
Stored in an Array Boxed Array elements are references themselves
Using === for reference comparison compile error Value classes have no stable reference identity

The following uses an interface to demonstrate boxing: the same value class is not boxed when passed as a concrete type, but is boxed when passed as an interface type.

Example

interface

Displayable

{

    fun display

(

)

:

String

}

@JvmInline

value

class

Meter

(

val value

:

Double

)

:

Displayable

{

    override fun display

(

)

:

String

=

"$value m"

}

// The parameter is the concrete type Meter, whose underlying value is just a double

fun half

(

m

:

Meter

)

:

Meter

=

Meter

(

m.

value

/

2

)

// The parameter is an interface type, so the passed Meter is boxed into an object

fun show

(

d

:

Displayable

)

:

String

=

d.

display

(

)

fun main

(

)

{

    val m

=

Meter

(

10.0

)

    println

(

half

(

m

)

.

value

)

    println

(

show

(

m

)

)

    println

(

m.

display

(

)

)

}

Running result:



5.0

10.0 m

10.0 m

Note:If a value class is used extensively, try to make function signatures use the value class itself directly rather than Any, interfaces, or generic containers, so that boxing overhead is truly saved.


Common questions

Do value classes support destructuring declarations?

No. A value class only generates equals、hashCode and toString, not componentN, so you cannot write val (v) = UserId(1)。

Can a value class be used as a Map key?

Yes. A value class overrides equals and hashCode, with semantics consistent with data classes; two instances with the same underlying value are treated as the same key in a Map.

Can value classes and data classes replace each other?

No. When you need multiple fields, need copy or destructuring, use a data class; when you only need to wrap a single value for type safety, use a value class.

Do value classes never allocate objects?

Not necessarily. As soon as nullability, generics, interfaces, or Any are involved, the compiler will box; whether boxing actually occurs can be confirmed by javap decompiling the bytecode.