Generic value class
- Kotlin course
- Intermediate
- Lesson 79/116
- 5 min
Learn to use generic value classes.
Generic value class
A value class can be generic. Example: @JvmInline value class Box<T>(val value: T). This provides a type-safe wrapper for any type without writing a separate class for each. Box<Int> and Box<String> are distinct types.
Usage: val a = Box(10) and val b = Box("Hello"). Type inference determines T automatically. A generic value class is also inlined to the underlying type at runtime; boxing happens only when assigned to an Any. This is the way to write flexible but type-safe wrappers.
Using a generic value class
When using a generic value class, type inference kicks in. In val a = Box(10) the compiler infers Box<Int>. You can also write Box<Int>(10) explicitly.
println(a.value) gives the wrapped value: 10. Box<String> and Box<Int> cannot be mixed; the compiler rejects it. A generic value class is useful for wrapping IDs, units of measure and labels in a type-safe way. At runtime each is stored as the underlying type.
Practice Define the Box<T> generic value class
Define @JvmInline value class Box<T>(val value: T). In main create val a = Box(10) and val b = Box("Hello"). Print with println(a.value) and println(b.value).
Starter code
// Define the Box value class: generic value class
// value: T single field
fun main() {
// Create Box<Int> and Box<String> and print
}Sample solution
@JvmInline
value class Box<T>(val value: T)
fun main() {
val a = Box(10)
val b = Box("Hello")
println(a.value)
println(b.value)
}Expected output
10 Hello
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does value class Box<T>(val value: T) allow?
- Only Int
- Any type Correct answer
- Only String
- Only classes
Explanation: The T type parameter accepts any type.
2 Complete the generic value class definition
@JvmInline
value class Box<____>(val value: T)
@JvmInline
value class Box<T>(val value: T)
Explanation: The T type parameter makes it generic.
3 Match the generic value class concepts
| Term | Meaning |
|---|---|
<T> |
Type parameter |
val value: T |
Generic field |
Box<Int> |
Int box |
Box<String> |
String box |