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
45: Inline Value Classes
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
KilometerscalledtoMeters()that returns aMetersinstance. - Add a member function to
MeterscalledtoKilometers()that returns aKilometersinstance. - Write a function
calculateTotalDistance(d1: Meters, d2: Meters): Metersthat 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.
There are no comments for now.