Kotlin

Inline Value Classes (kotlin 1.5+)

admin by @admin ADMIN
6h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`@JvmInline value class` wraps a single value with a distinct type at compile time but no runtime overhead — at runtime it's just the underlying primitive/object. Replaces typedef tricks and prevents UserId vs PostId mix-ups.
Kotlin
Raw
@JvmInline value class UserId(val raw: Long)
@JvmInline value class PostId(val raw: Long)
@JvmInline value class Email(val raw: String) {
    init { require(raw.contains("@")) { "not an email: $raw" } }
    val domain: String get() = raw.substringAfter("@")
}

fun deleteUser(id: UserId) { println("deleting user ${id.raw}") }

fun main() {
    val u = UserId(42L)
    val p = PostId(99L)

    deleteUser(u)             // ✓
    // deleteUser(p)          // ✗ compile error — different types
    // deleteUser(42L)        // ✗ compile error — Long isn't UserId

    val e = Email("alice@example.com")
    println(e.domain)         // example.com

    // At runtime, UserId is just a Long — zero memory overhead vs raw Long.
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.