Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introduction to Kotlin inline classes

Introduction to Kotlin inline classes

Avatar for Konrad Szewczuk

Konrad Szewczuk

November 26, 2019

Other Decks in Programming

Transcript

  1. “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” https://kotlinlang.org/docs/reference/inline-classes.html
  2. When you instantiate an inline class like this: the class

    isn’t actually instantiated in the compiled code. In fact, as far as the JVM is concerned, you’ve simply written this:
  3. • At runtime, an inline class can be represented as

    both, the wrapper type and the underlying type. The compiler prefers using the underlying (wrapped) type of an inline class to optimize the code as much as possible. • In certain situations, however, the compiler needs to use the wrapper itself, so it will be generated during compilation. How does inline classes work
  4. • Autoboxing can happen when you use an instance of

    an inline class where a super type is expected: Autoboxing
  5. • Autoboxing also can happens when you consider nullability: ◦

    nullability of the underlying type ◦ nullability at the usage site • Both cases can happen for underlying reference type or underlying primitive type Autoboxing
  6. • Inline class must have a public primary constructor with

    a single value parameter • Inline class must have a single read-only (val) property as an underlying value, which is defined in primary constructor • Underlying value cannot be of the same type that is containing inline class Limitations & restrictions
  7. • Inline class cannot have init block • Inline class

    must be final Inline class can implement only interfaces • Inline class must be a top level class • Inline class cannot have backing fields • Hence, it follows that inline class can have only simple computable properties (no lateinit/delegated properties) Limitations & restrictions
  8. Inline classes can be a good choice to use: •

    To indicate a unit of measure • To use types to protect user from misuse (https://jakewharton.com/inline-classes-make-great-database-ids/) Summary