Part 16 / Topic 4 of 5
Value classes
@JvmInline value class wraps exactly one value in a distinct type, catching mix-ups at
compile time that a bare String/Double parameter list never would -- and, on the JVM, with
little to no runtime cost, because the wrapper is usually erased down to its underlying value.
@JvmInline
value class ShipmentId(val value: String) {
init { require(value.startsWith("S-")) { "invalid shipment id: $value" } }
}
@JvmInline
value class Kilograms(val value: Double) {
operator fun plus(other: Kilograms) = Kilograms(value + other.value)
override fun toString() = "${value}kg"
}
// Without value classes, swapping these two String/Double arguments by accident would still
// compile -- the whole point of ShipmentId/Kilograms is making that a compile error instead.
fun book(id: ShipmentId, weight: Kilograms) = "booked ${id.value} at $weight"
booked S-2001 at 1200.0kg
total: 3600.0kg
bad id rejected: invalid shipment id: 2001
book()'s real JVM parameter types: [String, double]
book()'s mangled JVM method name starts with 'book-': true
Two things the last two lines prove, using the same reflection technique Part 15's exercise 8
used: book(ShipmentId, Kilograms) really does take a plain String and a plain double at
the JVM level -- ShipmentId/Kilograms disappear entirely at runtime for this signature,
confirmed with javap -p the same way Part 15 confirmed data class methods:
$ javap -p out/ShipmentId.class
public final class ShipmentId {
private final java.lang.String value;
public static java.lang.String constructor-impl(java.lang.String);
public static final ShipmentId box-impl(java.lang.String);
public final java.lang.String unbox-impl();
...
}
And book's real, mangled JVM name (something like book-DCSynkk, varying by compiler build)
is why the method-name check above only tests startsWith("book-") rather than an exact string:
the JVM doesn't let you overload a method by return type or by an erased-away wrapper type
alone, so Kotlin appends a short, stable-per-signature suffix to keep book(ShipmentId, Kilograms) from silently colliding with some other book(String, Double) overload elsewhere in
the same file.
Full program: examples/04_value_classes.kt.
Done here? The practice set for Part 16 — including the solutions — is on the part page.