Skip to Content
Course content

134: Value Classes and Inline Classes Revisited

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

Imagine you're organizing a massive warehouse. You have thousands of identical-looking silver keys. Some open locker A, some open locker B, and some open the main office. If you just throw them all in a bowl, they're all just "pieces of metal" to you. You might try to open the office door with a locker key, and while the key fits in the lock, it won't turn. You've wasted time and potentially caused a headache because you treated two different things as the same because they looked the same.

Now, imagine you attach a tiny, weightless colored ribbon to each key. A red ribbon for the office, blue for locker A. The ribbon doesn't make the key heavier or bulkier—it doesn't change the physical nature of the key—but it gives you a visual signal that prevents you from using the wrong one. That is exactly what value classes do for your data.

The Danger of Primitive Obsession

In a lot of the code I've inherited over the years, I see something called "Primitive Obsession." It's when a developer uses a Long for a User ID, a Long for an Order ID, and a Long for a Product ID. At first, it seems efficient. But then you end up with a function like this:

fun processOrder(userId: Long, orderId: Long, productId: Long) { 
    // ... 
}

It is incredibly easy to accidentally swap userId and orderId when calling this function. The compiler won't blink an eye because, as far as it's concerned, you're just passing three Longs. You only find out you've swapped them when the database returns "Order Not Found" or, worse, when you update the wrong user's record.

Wrapping Without the Weight

You could solve this by creating standard wrapper classes, but then you're allocating a new object on the heap for every single ID. In a high-throughput system, that's a lot of unnecessary garbage collection pressure. This is where the value class (which evolved from the experimental inline class) comes in.

By using @JvmInline value class, you tell Kotlin: "I want this to be a distinct type during development, but when you compile this to bytecode, just treat it as the underlying primitive."

@JvmInline
value class UserId(val value: Long)

@JvmInline
value class OrderId(val value: Long)

@JvmInline
value class ProductId(val value: Long)

fun processOrder(userId: UserId, orderId: OrderId, productId: ProductId) {
    println("Processing order ${orderId.value} for user ${userId.value}")
}

// This now fails at compile time!
// processOrder(OrderId(123), UserId(456), ProductId(789)) 

I love this approach because it gives us the best of both worlds. You get the type safety of a full-blown class, but the runtime performance of a primitive. The "ribbon" is stripped off during compilation, leaving only the "metal key."

Where the Magic (and the Limitations) Lie

It's not all magic, though. There are a few things I want you to keep in mind so you don't hit a wall. First, a value class can only have one property in its primary constructor. If you need two or more, you're back to using a standard data class.

Second, be careful with generics. If you use a value class where a generic type (like List<T>) is expected, the compiler will "box" the value—meaning it will actually create an object wrapper. In that specific case, you lose the performance benefit, though you still keep the type safety. I usually find this trade-off acceptable, but if you're writing a tight loop processing millions of IDs in a list, it's something to watch out for.

Lastly, remember that value classes can have init blocks and methods. You can add validation logic right into the init block to ensure that a UserId is never negative, for example. This turns your IDs from "dumb numbers" into "smart types" that protect your business logic.




📋 Practical Task

Implementation: Type-Safe Currency and Account System

You are building a simplified banking module. To prevent the catastrophic error of adding different currencies together or swapping an Account ID with a Transaction ID, you need to implement value classes.

Requirements:

  • Create a @JvmInline value class AccountId that wraps a String.
  • Create a @JvmInline value class CurrencyAmount that wraps a Double.
  • Implement a function transferFunds(from: AccountId, to: AccountId, amount: CurrencyAmount) that prints a confirmation message.
  • In your main function, attempt to call transferFunds.
  • Try to intentionally pass a raw String or a Double instead of the value classes and observe the compiler error.
  • Add an init block to CurrencyAmount that throws an IllegalArgumentException if the amount is negative.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.