Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
134: Value Classes and Inline Classes Revisited
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 AccountIdthat wraps aString. - Create a
@JvmInline value class CurrencyAmountthat wraps aDouble. - Implement a function
transferFunds(from: AccountId, to: AccountId, amount: CurrencyAmount)that prints a confirmation message. - In your
mainfunction, attempt to calltransferFunds. - Try to intentionally pass a raw
Stringor aDoubleinstead of the value classes and observe the compiler error. - Add an
initblock toCurrencyAmountthat throws anIllegalArgumentExceptionif the amount is negative.
There are no comments for now.