value class
- Kotlin course
- Intermediate
- Lesson 76/116
- 5 min
Learn wrappers with @JvmInline value class.
value class
A value class wraps a single value and provides type safety with zero overhead. It is declared with the @JvmInline annotation and the value class keyword. Example: @JvmInline value class UserId(val id: String).
At compile time UserId is checked as a distinct type; at runtime only the inner String is stored, with no wrapper object. This gives type safety without boxing. Using UserId instead of String makes mixing it with an OrderId a compile error.
value class constraints
A value class primary constructor must contain exactly one val parameter. A second field cannot be added; if multiple fields are needed use a data class. The parameter must be marked val.
Example: @JvmInline value class UserId(val id: String) is valid. value class UserId(val id: String, val n: Int) is invalid because it has two fields. Value classes cannot be open, abstract or sealed; inheritance is closed. But they can implement interfaces and contain methods.
Practice Define the UserId value class
Define @JvmInline value class UserId(val id: String). In main create val u = UserId("U1") and print it with println(u).
Starter code
// Define the UserId value class: value class with a single id field
fun main() {
// Create a UserId instance and print it
}Sample solution
@JvmInline
value class UserId(val id: String)
fun main() {
val u = UserId("U1")
println(u)
}Expected output
U1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which annotation does a value class require?
- @Value
- @Inline
- @JvmInline Correct answer
- @Data
Explanation: @JvmInline is required for a value class.
2 Complete the value class definition
@JvmInline ____ class UserId(val id: String)
@JvmInline value class UserId(val id: String)
Explanation: value class UserId is a single-field wrapper.
3 Match the value class parts
| Term | Meaning |
|---|---|
@JvmInline |
Annotation |
value class |
Wrapper |
val id: String |
Single field |
UserId |
Type |