Skip to Content
Course content

45: Inline Value Classes

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why not just use a typealias?

I get this question a lot. If you have a String that represents a UserId, your first instinct might be to write typealias UserId = String. It looks clean, right? But here's the catch: a typealias is just a nickname. The compiler doesn't actually treat it as a new type.

If you have a function like fun deleteUser(id: UserId), and you accidentally pass in a SessionToken (which is also a typealias for String), Kotlin won't blink an eye. You've just deleted a user using a session token. That's a bug waiting to happen.

Value classes solve this by creating a real type that the compiler respects, but without the performance hit of a full wrapper class. Check this out:

@JvmInline
value class UserId(val value: String)

@JvmInline
value class SessionToken(val value: String)

fun deleteUser(id: UserId) { 
    println("Deleting user ${id.value}") 
}

// This will now fail to compile, which is exactly what we want:
// deleteUser(SessionToken("abc-123")) 

Does this actually slow down my app with all these wrappers?

That's the "magic" part of value classes. Under the hood, the Kotlin compiler tries to "inline" the value. In most cases, the UserId object never actually exists at runtime; the JVM just sees a plain String. You get the type safety of a class during development, but the performance of a primitive at runtime.

I should mention the @JvmInline annotation. You'll see it everywhere with value classes on the JVM. It's required because the compiler needs an explicit signal that it's okay to mangle the bytecode to make this inlining happen. If you're targeting Kotlin/JS or Native, the requirements differ slightly, but for most of us on the JVM, just remember: no annotation, no value class.

Can I actually put logic inside a value class?

Absolutely. This is where they really start to beat out simple primitives. Since it's still a class, you can add init blocks for validation and member functions for utility. I love using this for things like "Password" types where I want to ensure the value isn't empty before it even enters my business logic.

@JvmInline
value class Password(val value: String) {
    init {
        require(value.length >= 8) { "Password must be at least 8 characters long!" }
    }

    fun mask(): String = "*".repeat(value.length)
}

val myPass = Password("secure123")
println(myPass.mask()) // Output: *********

Just keep in mind that a value class can only have one read-only property. If you find yourself needing a second property, you've outgrown a value class and need a regular data class.

When should I avoid using them?

Value classes are great, but they aren't a silver bullet. One major limitation is that they can't extend other classes. They are final. If you need a complex class hierarchy, value classes are out.

Also, be aware of "boxing." If you use a value class as a generic type (like putting it in a List<UserId>), Kotlin has to "box" it—meaning it creates a real object on the heap to satisfy the JVM's type system. If you're doing this in a tight loop with millions of objects, you might lose that performance edge I mentioned earlier. It's still usually faster than a standard wrapper, but it's something to keep an eye on if you're optimizing for extreme performance.




📋 Practical Task

Building a Type-Safe Distance Calculator

Imagine you are building a mapping app. You have distances measured in Meters and Kilometers. To prevent the catastrophic bug of adding meters to kilometers without converting them, you need to implement value classes.

  • Create a @JvmInline value class Meters(val value: Double).
  • Create a @JvmInline value class Kilometers(val value: Double).
  • Add a member function to Kilometers called toMeters() that returns a Meters instance.
  • Add a member function to Meters called toKilometers() that returns a Kilometers instance.
  • Write a function calculateTotalDistance(d1: Meters, d2: Meters): Meters that sums two meter values.

Test your implementation by creating a Kilometers object, converting it to Meters, and passing it into your calculateTotalDistance function along with another Meters object.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.