Inline classes

Inline classes are available only since Kotlin 1.3 and currently in Alpha. See details below

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, while their wrappers don’t get any special treatment.

To solve such issues, Kotlin introduces a special kind of class called an inline class, which is declared by placing an inline modifier before the name of the class:

  1. inline class Password(val value: String)

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 (see details about runtime representation below):

  1. // No actual instantiation of class 'Password' happens
  2. // At runtime 'securePassword' contains just 'String'
  3. val securePassword = Password("Don't try this in production")

This is the main feature of inline classes, which inspired the name “inline”: data of the class is “inlined” into its usages (similar to how content of inline functions is inlined to call sites).

Members

Inline classes support some functionality of regular classes. In particular, they are allowed to declare properties and functions:

  1. inline class Name(val s: String) {
  2. val length: Int
  3. get() = s.length
  4. fun greet() {
  5. println("Hello, $s")
  6. }
  7. }
  8. fun main() {
  9. val name = Name("Kotlin")
  10. name.greet() // method `greet` is called as a static method
  11. println(name.length) // property getter is called as a static method
  12. }

However, there are some restrictions for inline class members:

  • inline classes cannot have init blocks
  • inline class properties cannot have backing fields
    • it follows that inline classes can only have simple computable properties (no lateinit/delegated properties)

Inheritance

Inline classes are allowed to inherit from interfaces:

  1. interface Printable {
  2. fun prettyPrint(): String
  3. }
  4. inline class Name(val s: String) : Printable {
  5. override fun prettyPrint(): String = "Let's $s!"
  6. }
  7. fun main() {
  8. val name = Name("Kotlin")
  9. println(name.prettyPrint()) // Still called as a static method
  10. }

It is forbidden for inline classes to participate in a class hierarchy. This means that inline classes cannot extend other classes and must be final.

Representation

In generated code, the Kotlin compiler keeps a wrapper for each inline class. Inline class instances can be represented at runtime either as wrappers or as the underlying type. This is similar to how Int can be represented either as a primitive int or as the wrapper Integer.

The Kotlin compiler will prefer using underlying types instead of wrappers to produce the most performant and optimized code. However, sometimes it is necessary to keep wrappers around. As a rule of thumb, inline classes are boxed whenever they are used as another type.

  1. interface I
  2. inline class Foo(val i: Int) : I
  3. fun asInline(f: Foo) {}
  4. fun <T> asGeneric(x: T) {}
  5. fun asInterface(i: I) {}
  6. fun asNullable(i: Foo?) {}
  7. fun <T> id(x: T): T = x
  8. fun main() {
  9. val f = Foo(42)
  10. asInline(f) // unboxed: used as Foo itself
  11. asGeneric(f) // boxed: used as generic type T
  12. asInterface(f) // boxed: used as type I
  13. asNullable(f) // boxed: used as Foo?, which is different from Foo
  14. // below, 'f' first is boxed (while being passed to 'id') and then unboxed (when returned from 'id')
  15. // In the end, 'c' contains unboxed representation (just '42'), as 'f'
  16. val c = id(f)
  17. }

Because inline classes may be represented both as the underlying value and as a wrapper, referential equality is pointless for them and is therefore prohibited.

Mangling

Since inline classes are compiled to their underlying type, it may lead to various obscure errors, for example unexpected platform signature clashes:

  1. inline class UInt(val x: Int)
  2. // Represented as 'public final void compute(int x)' on the JVM
  3. fun compute(x: Int) { }
  4. // Also represented as 'public final void compute(int x)' on the JVM!
  5. fun compute(x: UInt) { }

To mitigate such issues, functions using inline classes are mangled by adding some stable hashcode to the function name. Therefore, fun compute(x: UInt) will be represented as public final void compute-<hashcode>(int x), which solves the clash problem.

Note that - is an invalid symbol in Java, meaning that it’s impossible to call functions which accept inline classes from Java.

Inline classes vs type aliases

At first sight, inline classes may appear to be very similar to type aliases. Indeed, both seem to introduce a new type and both will be represented as the underlying type at runtime.

However, the crucial difference is that type aliases are assignment-compatible with their underlying type (and with other type aliases with the same underlying type), while inline classes are not.

In other words, inline classes introduce a truly new type, contrary to type aliases which only introduce an alternative name (alias) for an existing type:

  1. typealias NameTypeAlias = String
  2. inline class NameInlineClass(val s: String)
  3. fun acceptString(s: String) {}
  4. fun acceptNameTypeAlias(n: NameTypeAlias) {}
  5. fun acceptNameInlineClass(p: NameInlineClass) {}
  6. fun main() {
  7. val nameAlias: NameTypeAlias = ""
  8. val nameInlineClass: NameInlineClass = NameInlineClass("")
  9. val string: String = ""
  10. acceptString(nameAlias) // OK: pass alias instead of underlying type
  11. acceptString(nameInlineClass) // Not OK: can't pass inline class instead of underlying type
  12. // And vice versa:
  13. acceptNameTypeAlias(string) // OK: pass underlying type instead of alias
  14. acceptNameInlineClass(string) // Not OK: can't pass underlying type instead of inline class
  15. }

Alpha status of inline classes

The design of inline classes is in Alpha, meaning that no compatibility guarantees are given for future versions. When using inline classes in Kotlin 1.3+, a warning will be reported, indicating that this feature has not been released as stable.

To remove the warning you have to opt in to the usage of this feature by passing the compiler argument -Xinline-classes.

Enabling inline classes in Gradle

  1. kotlin {
  2. sourceSets.all {
  3. languageSettings.enableLanguageFeature('InlineClasses')
  4. }
  5. }
  1. kotlin {
  2. sourceSets.all {
  3. languageSettings.enableLanguageFeature("InlineClasses")
  4. }
  5. }

See Compiler options in Gradle for details. For multiplatform projects, see language settings.

Enabling inline classes in Maven

  1. <configuration>
  2. <args>
  3. <arg>-Xinline-classes</arg>
  4. </args>
  5. </configuration>

See Compiler options in Maven for details.

Further discussion

See this language proposal for inline classes for other technical details and discussion.