0
0
KotlinConceptBeginner · 3 min read

What is Value Class in Kotlin: Simple Explanation and Example

A value class in Kotlin is a special kind of class that wraps a single value without the usual object overhead. It helps improve performance by avoiding extra memory allocation while keeping type safety.
⚙️

How It Works

A value class in Kotlin is like a wrapper around one value, such as a number or a string. Imagine you have a box that holds exactly one item. Normally, when you use a class, the box itself takes up space in memory along with the item inside. But with a value class, Kotlin tries to remove the box and just keep the item, so it uses less memory and runs faster.

This works because Kotlin uses a technique called "inline" for value classes. When you use a value class, the compiler replaces the class with the actual value inside it during the program's run. This means no extra object is created, but you still get the benefits of having a special type that helps avoid mistakes, like mixing up different kinds of values.

💻

Example

This example shows a value class that wraps an Int to represent a user ID. It behaves like a normal class but is optimized by Kotlin.

kotlin
@JvmInline
value class UserId(val id: Int)

fun greetUser(userId: UserId) {
    println("Hello, user #${userId.id}!")
}

fun main() {
    val user = UserId(42)
    greetUser(user)
}
Output
Hello, user #42!
🎯

When to Use

Use value classes when you want to create a type that wraps a single value but want to avoid the cost of creating a full object. This is helpful for things like IDs, money amounts, or other simple data where you want to add meaning and safety without slowing down your program.

For example, if you have different kinds of IDs (user ID, product ID), using value classes prevents accidentally mixing them up. Also, because they are optimized, they are great for performance-sensitive code where many small objects would otherwise be created.

Key Points

  • Value classes wrap a single value and avoid extra memory use.
  • Kotlin replaces value classes with their underlying value at runtime.
  • They improve type safety by creating distinct types.
  • Useful for simple data like IDs, amounts, or wrappers.
  • Require Kotlin 1.5 or higher.

Key Takeaways

Value classes wrap one value without extra object overhead.
They improve performance by inlining the wrapped value.
Use them to add type safety for simple data types.
They require Kotlin 1.5 or newer.
Ideal for IDs, money, or other single-value wrappers.