In every programming language, classes hold values and functions. Kotlin has introduced Value classes that can hold only a single value, making them faster and lighter. To declare a value class, we have to use the value keyword and they cannot be extended. Value classes are always annotated with @JvmInline annotation in Kotlin.
Inline Value Classes in Kotlin: A Beginner’s Guide
Why value classes faster than normal classes?
Value classes store only a single value which makes the statement inline. When we annotate a value class with @JvmInline annotation, It tells the compiler to store variable value directly into memory which is eventually required by normal classes at the time of memory allocation.
How to declare value classes in Kotlin?
To declare a value class in Kotlin we will use the value keyword and also @JvmInline annotation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@JvmInline value class UserName(val value: String) fun printUserName(userName: UserName) { println("User Name is : ${userName.value}") } fun main() { val userName = UserName("kotlinGuide27") printUserName(userName) } // Output // User Name is : kotlinGuide27 |
Conclusion
Values classes are memory efficient and faster than other classes but they can only support a single value, so it is a drawback for them. But with a single value, they are quite good. So it’s completely up to us how to use value classes in Kotlin and depends on our data requirements.