What is inline class in Kotlin and when do we need one? Provide an example.

Technology CommunityCategory: KotlinWhat is inline class in Kotlin and when do we need one? Provide an example.
VietMX Staff asked 4 years ago

Sometimes it is necessary for business logic to create a wrapper around some type. However, it introduces runtime overhead due to additional heap allocations. Moreover, if the wrapped type is primitive, the performance hit is terrible, because primitive types are usually heavily optimized by the runtime.

Inline classes provide us with a way to wrap a type, thus adding functionality and creating a new type by itself. As opposed to regular (non-inlined) wrappers, they will benefit from improved performance. This happens because the data is inlined into its usages, and object instantiation is skipped in the resulting compiled code.

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
}

Some notes about inline classes:

  • A single property initialized in the primary constructor is the basic requirement of an inline class
  • Inline classes allow us to define properties and functions just like regular classes
  • Init blocks, inner classes, and backing fields are not allowed
  • Inline classes can inherit only from interfaces
  • Inline classes are also effectively final