Methods
- Kotlin course
- Intermediate
- Lesson 78/116
- 5 min
Learn to define methods in value classes.
value class methods
A value class can contain methods like a regular class. Example: @JvmInline value class UserId(val id: String) { fun display() = println("User: $id") }. The method accesses the wrapped value through the id property.
Inside a value class this represents the wrapped value. Methods can also be added as extensions. This is a clean way to attach behavior to a value: type safety and behavior unite in one definition. At runtime method calls are resolved statically; there is no overhead.
Methods and inner access
A method inside a value class accesses the wrapped value directly. In fun display() = println("User: $id") the id property is the wrapped value. You can also write this.id explicitly.
Methods can also return values: fun uppercase() = id.uppercase() returns a new String. Value class methods are inlined at runtime, so there is no call overhead. This makes it efficient to put small helper methods inside a value class.
Practice Add a display method to UserId
Define @JvmInline value class UserId(val id: String) with fun display() = println("User: $id") inside. In main create val u = UserId("U1") and call u.display().
Starter code
// 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
@JvmInline
value class UserId(val id: String) {
fun display() = println("User: $id")
}
fun main() {
val u = UserId("U1")
u.display()
}Expected output
User: U1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the method parts
| Term | Meaning |
|---|---|
fun display() |
Method |
value class |
Wrapper |
val id |
Field |
this.id |
Inner access |
2 Can a value class contain methods?
- Yes Correct answer
- No
- Only static
- Only getter
Explanation: A value class can contain methods like a regular class.
3 Complete the display body
@JvmInline
value class UserId(val id: String) {
fun display() = println("User: $____")
}
@JvmInline
value class UserId(val id: String) {
fun display() = println("User: $id")
}
Explanation: display prints the id property.