CodeBlanks Logo Icon CodeBlanks

Summary - Value class

Combine value class, methods and type safety to write a UserId class.

Summary - Value class

In this group you learned five aspects of value class. An @JvmInline value class wraps a single value with zero overhead. Type safety gives distinct types like UserId and OrderId.

A value class can contain methods; behavior accesses the wrapped value. A generic value class Box<T> wraps any type. Compared with a data class, a value class suits one field and a data class suits many. Each tool combines compile-time safety with runtime efficiency.

When to use value class?

Use a value class when you want to wrap a single value in a type-safe way: IDs, emails, units, labels. Choose a data class when multiple fields or copy/equals are needed.

A value class is a distinct type at compile time and the underlying type at runtime. This prevents mix-ups without extra memory. Methods and generic type parameters are also supported, so a wrapper carries behavior as well as a value. Picking the right tool keeps both safety and performance.

Practice Define a value class with a method

Define @JvmInline value class UserId(val id: String) with fun display() = println("User: $id") inside. In main call UserId("U1").display().

Starter code

Main.kt
// Define the UserId value class: with a display method
// The display method: prints User: $id

fun main() {
    // Create a UserId instance and call display
}

Sample solution

Main.kt
@JvmInline
value class UserId(val id: String) {
    fun display() = println("User: $id")
}

fun main() {
    UserId("U1").display()
}

Expected output

User: U1

Practice Use the generic Box<T>

Define @JvmInline value class Box<T>(val value: T). In main call println(Box(10).value) and println(Box("Hello").value).

Starter code

Main.kt
// Define the Box value class: generic value class

fun main() {
    // Create Box<Int> and Box<String> and print
}

Sample solution

Main.kt
@JvmInline
value class Box<T>(val value: T)

fun main() {
    println(Box(10).value)
    println(Box("Hello").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 is the main benefit of value class?

  • More fields
  • Automatic copy
  • Inheritance
  • Type safety, zero cost Correct answer

Explanation: A value class provides type safety with zero overhead.

2 Match the value class concepts

Term Meaning
@JvmInline value class Wrapper
single val field Required
fun display() Method
Box<T> Generic

All lessons in Intermediate