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.
The above method has two problems:
These two problems are overcome by Inline classes
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”).
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.
These classes are allowed to inherit from Interfaces but can not extend other classes and must be final
Inline classes can be represented as either wrappers or underlying type.Though the latter is preferred, sometimes it is useful to keep wrappers around.Necessarily they are boxed whenever used as other type. Referential equality is meaningless as it can be represented both as an underlying value and as a wrapper.
As an underlying type, these inline classes may lead to obscure errors like platform signature crashes.
To prevent such errors we use a process called Mangling where we add some hashcode to function name.Therefore, fun compute(x: UInt) will be represented as public final void compute-(int x), which solves the problem.
Inline classes vs type aliases
Though both may appear similar, the type aliases are assignment-compatible with underlying type. Also inline classes introduce a completely new type whereas type aliases give an alternate name for existing type
The design of inline classes is new and no compatibility guarantees are given.In Kotlin 1.3+, a warning will be reported, indicating that this feature is experimental.To remove this we have to opt in to the usage of this experimental feature by passing the compiler argument -Xinline-classes.