Intro to Kotlin’s Inline Classes
Inline classes are a new language feature in Kotlin and they are currently in alpha. Inline classes are simple wrapper classes that are optimized by the Kotlin runtime to avoid the performance hit of initializing a class.
Let’s look at a few examples.
class PhoneNumber(val number: String)
This is a standard Kotlin class and is perfectly usable. However, classes are more expensive to initialize than fields. These classes have an especially high cost if you are wrapping a primitive, because primitives in Kotlin are heavily optimized by the runtime. This class wouldn’t get any of those optimizations.
Alternatively we could just have the phone number be a property that lives in another class a la:
val phoneNumber: String
Of course we now lose type safety and could assign any ole String to phoneNumber.
There must be a better way! And there is: Inline classes.
inline class PhoneNumber(val number: String)
This class will give us class type safety at the same performance price of a field. Let’s instantiate the class with…
val phoneNumber: PhoneNumber = PhoneNumber("555-867-5309")
The Kotlin runtime will recognize this simply as
val phoneNumber: String = "555-867-5309"
but we get to rely on the PhoneNumber type in code, pass it into methods, etc.
Inline class vs Typealias
You may be asking yourself what the difference is between an inline class and a typealias. And you would be asking yourself a good question.
Inline classes and typealiases are very similar. The main difference is that a typealias is interchangeable with the type it is wrapping.
typealias PhoneNumber = String val phoneNumber: PhoneNumber = "555-857-5309"
Notice here, we are assigning a PhoneNumber typealias to a String value. We aren’t instantiating a PhoneNumber object. We can even pass this phoneNumber object into methods that accept a String. However,
inline class PhoneNumber(val number: String) val phoneNumber: PhoneNumber = "555-867-5309"
This will not compile. Our phoneNumber object is typed to PhoneNumber, so we must instantiate a PhoneNumber class as we did above.