Members
They are similar to regular classes in the sense that they are allowed to declare properties and functions.However, they have certain limitations too.Inline classes cannot have init blocks nor can they have complex computable properties like lateinit/delegated properties.
Java
inline class Name(val s: String) { val length: Int get() = s.length fun greet() { println( "Hello, $s" ) } } fun main() { val name = Name( "Kotlin" ) name.greet() // method `greet` is called as a static method println(name.length) // property getter is called as a static method } |
Kotlin Inline classes
Inline classes are introduced by Kotlin since Kotlin 1.3 version to overcome the shortcomings of traditional wrappers around some types.These Inline classes add the goodness of Typealiases with the value range of the primitive data types.
Let us suppose that we are selling some items and the cost is defined as a float type.This is depicted in the following data class
data class Items(val itemno: Int, val cost: float, val qty: Int)
If we support two types of currencies like dollar and rupees, we need to refactor cost in another class.
Java
data class Items(val itemno: Int, val cost: Cost, val qty: Int) data class Cost(val value: Float, val currency: Currency) enum class Currency { RUPEE, DOLLAR } |
The above method has two problems:
1.Memory overhead
2.Complexity
These two problems are overcome by Inline classes
Java
data class Item(val id: Int, val price: RupeePrice, val qty: Int) inline class RupeePrice(val price: Float) { inline fun toDollars(): Float = price * 71 .62f } |
An inline class must have a single property initialized in the primary constructor. At runtime, instances of the inline class will be represented using this single property:data of the class is “inlined” into its usages (That’s why the name “Inline classes”).