Kotlin value classes and sealed interfaces for domain modeling
How Kotlin value class boxing and name mangling work, modeling business failures with sealed interfaces vs. Result, and handling Spring and Jackson boundaries.
Swapping two
Longarguments by accident and throwing generic exceptions for every business failure created subtle bugs in a course enrollment service. I introduced Kotlinvalue classandsealed interfaceto make those mistakes unrepresentable at compile time. This post covers boxing rules, name mangling, howsealed interfacecompares toResult, and the friction points at Spring and Jackson boundaries.
Tested with Kotlin 1.9.10, Spring Boot 3.1.4, jackson-module-kotlin 2.15 (Spring Boot managed), and Java 17.
Background
In a study project’s course enrollment module, I accidentally swapped the arguments in enroll(memberId: Long, courseId: Long). Because both parameters were plain Long values, the compiler stayed silent. Worse, the test fixture IDs happened to overlap, so the bug slipped past my first round of tests.
Error handling had a similar problem. The service threw IllegalStateException for every domain failure—”course full,” “already enrolled,” and “outside enrollment window.” Nothing in the method signature told callers which failures could happen, and the controller ended up parsing exception message strings just to pick an HTTP status code.
In my post on Kotlin JPA entity design, I covered keeping JPA entities as plain class definitions. This time, the focus is on tightening the value types and return types flowing in and out of domain logic.
How value class boxing and name mangling work
A @JvmInline value class MemberId(val value: Long) acts as a distinct type at compile time, while the Kotlin compiler unboxes it down to a raw long in bytecode wherever possible. You get compile-time type safety without paying for a wrapper object on every call.
Unboxing isn’t guaranteed everywhere, though. According to the Kotlin specification, a value class is boxed into a wrapper object whenever it is used as:
- A generic type argument (
List<MemberId>,Map<MemberId, Course>) - An interface type that the value class implements
- A nullable type (
MemberId?) when wrapping a primitive likeLong
The second detail that catches teams off guard is name mangling. In bytecode, fun enroll(memberId: MemberId, courseId: CourseId) and fun enroll(memberId: Long, courseId: Long) would collide into the same JVM method descriptor. To prevent that, the compiler appends a hash suffix to functions that accept a value class, turning enroll into something like enroll-AbC12de. Any Java caller or reflection-based framework looking up enroll by its Kotlin name will fail to find it.
flowchart TD
A["Kotlin source: MemberId type"] --> B{"Usage site"}
B -->|"Regular parameter or field"| C["Unboxed to primitive long"]
B -->|"Generic, interface, or nullable"| D["Boxed as MemberId wrapper"]
C --> E["Method name mangled with hash"]
Modeling business failures with sealed interface
For expected domain failures, I replaced exceptions with a closed sealed interface hierarchy. Because all subtypes must live in the same package and module, the compiler knows every possible branch. Since Kotlin 1.7, exhaustive checking applies to when statements as well as expressions—so adding a new failure case immediately breaks the build everywhere that doesn’t handle it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// src/main/kotlin/com/example/course/domain/EnrollmentResult.kt
package com.example.course.domain
@JvmInline
value class MemberId(val value: Long) {
init {
require(value > 0) { "MemberId must be positive: $value" }
}
}
@JvmInline
value class CourseId(val value: Long)
sealed interface EnrollmentResult {
data class Success(val enrollmentId: Long) : EnrollmentResult
sealed interface Failure : EnrollmentResult {
data class CapacityExceeded(val capacity: Int) : Failure
data class AlreadyEnrolled(val memberId: MemberId) : Failure
data object OutOfPeriod : Failure
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/main/kotlin/com/example/course/application/EnrollmentService.kt
package com.example.course.application
import com.example.course.domain.CourseId
import com.example.course.domain.EnrollmentResult
import com.example.course.domain.EnrollmentResult.Failure
import com.example.course.domain.MemberId
class EnrollmentService(
private val enrolledMembers: MutableSet<Long> = mutableSetOf(),
private val capacity: Int = 30,
private val isOpen: () -> Boolean = { true },
) {
fun enroll(memberId: MemberId, courseId: CourseId): EnrollmentResult = when {
!isOpen() -> Failure.OutOfPeriod
memberId.value in enrolledMembers -> Failure.AlreadyEnrolled(memberId)
enrolledMembers.size >= capacity -> Failure.CapacityExceeded(capacity)
else -> {
enrolledMembers += memberId.value
EnrollmentResult.Success(enrollmentId = courseId.value * 1_000 + enrolledMembers.size)
}
}
}
fun EnrollmentResult.toHttpStatus(): Int = when (this) {
is EnrollmentResult.Success -> 201
is Failure.CapacityExceeded -> 409
is Failure.AlreadyEnrolled -> 409
Failure.OutOfPeriod -> 400
}
data object, stabilized in Kotlin 1.9.0, gives singleton failure cases like OutOfPeriod a clean toString() instead of an object hash. With MemberId and CourseId in place, calling enroll(courseId, memberId) fails to compile immediately.
Comparing exceptions, Result, and sealed interfaces
| Mechanism | Failure representation | Compiler check | Best fit |
|---|---|---|---|
Exceptions (throw) | Hidden from signature | None | Unrecoverable errors and programming bugs |
kotlin.Result<T> | Fixed to Throwable | Success / failure only | Wrapping an external call that throws |
sealed interface | Typed data classes per case | Exhaustive when | Expected business failures callers must branch on |
kotlin.Result<T> only stores a Throwable on the failure path, so carrying structured payload data—like the current capacity on CapacityExceeded—still forces you back into custom exception classes. On top of that, runCatching catches every Throwable, which can swallow coroutine CancellationException and break structured cancellation if you aren’t careful.
It’s just as important to draw a clear line for when not to use them. Wrapping unrecoverable failures like database connection drops or null-pointer bugs in a sealed result only clutters every caller with branches that can’t actually recover. Keep those as exceptions and translate them centrally in @RestControllerAdvice. The same rule applies to value class: wrapping arbitrary counters or plain numbers with no validation or mix-up risk adds boilerplate for zero gain. Reserve value class for identifiers that must not be swapped and domain values with invariants.
Handling Spring and Jackson boundaries
Inside the domain layer, both features worked cleanly. The friction showed up right at the framework edges. My solution was to keep controller parameters, request/response DTOs, and JPA entity fields as raw primitives, then convert into MemberId(request.memberId) right as execution enters the application service.
Be careful exposing value classes directly to frameworks. Because methods taking a
value classhave mangled names, Spring Framework 6.0 controller handlers,@Transactionalproxies, and Java-based library callbacks can fail to invoke them as expected via reflection. Jackson serialization ofvalue classandsealedhierarchies also varies acrossjackson-module-kotlinversions, so lock down the exact JSON wire format with tests before exposing them in DTOs. If you genuinely need to serialize a sealed hierarchy, declare@JsonTypeInfowith an explicit discriminator property so deserialization can resolve the subtype.
If Java code needs to call a Kotlin function that accepts a value class, you can attach @JvmName("enrollByIds") to replace the mangled name with a stable JVM symbol. Because that puts signature-collision management back on you, I limit @JvmName to deliberate interop boundaries.
Checklist
- Apply
@JvmInline value classonly to identifiers that shouldn’t be mixed up (MemberId,CourseId) or values with real validation rules. - Avoid placing value classes in collections, nullable positions, or behind interfaces on allocation-sensitive paths.
- Model expected business failures as a
sealed interfaceand leave unrecoverable infrastructure faults as exceptions. - Keep
whenblocks free of catch-allelsebranches so the compiler flags unhandled failure subtypes. - Convert to and from primitives at controller, DTO, and JPA entity boundaries, and pin the JSON format with tests.