Kotlin: Type Aliases and Inline Classes
The Kotlin programming language has two distinct features that may be used for similar purposes. Those are inline classes and type aliases. You could use them to improve code clarity and type safety, but what’s the difference between them? This is the topic of this article.
Type Aliases
Type aliases first appeared in Kotlin version 1.1. They effectively allow you to declare a new name for any existing type. This declaration doesn’t create a new type, and you can pass the aliased type wherever the alias is expected (something that’s called assignment compatibility):
typealias Str = String
val s: Str = "Hello"
This example is probably not very useful. Let’s apply type alias to make a complex generic type more readable. Suppose we have two classes, Customer and Division, and we need to implement some processing of customers grouped by division:
data class Customer(val name: String)
data class Division(val name: String)
typealias CustomersByDivisionMap = Map<Division, List<Customer>>
class Processor {
fun processCustomers(customers: CustomersByDivisionMap) {
customers.forEach { entry ->
println(entry.key)
entry.value.forEach(::println)
}
}
}
We could save more characters by aliasing the type Map<Division, List<Customer>> to something even shorter, but I chose to create a more descriptive type name. As you see, we don’t need to cast or extract the value of the type from the alias — inside the method, we use the customers variable just as if it were a Map, which it is.
So this is how you could call the method that accepts this alias:
Processor().processCustomers(
mapOf(
Division("North")
to listOf(Customer("John"), Customer("Mary")),
Division("South")
to listOf(Customer("Fred"), Customer("Jill"))
)
)
Note that I pass a regular map to this method, although it accepts a type alias.
If I now decompile the generatedProcessor.class class to Java (e.g. using thejavap utility), I’ll see the following:
public final class Processor {
public final void processCustomers(
Map<Division, ? extends List<Customer>>);
public Processor();
}
So the alias was just replaced with the original type. This hints at an important limitation — the compiler won’t allow you to have a clash of two methods with the same signature, differing only in argument type aliases. E.g. this won’t work:
fun processCustomers(customers: CustomersByDivisionMap) { }
fun processCustomers(customers: Map<Division, List<Customer>>) { }
The first method will be replaced with the same signature as the second, which is not allowed in the target Java code.
Inline Types
Inline types were first introduced in Kotlin 1.3. Moreover, they are still (as of version 1.3.72) in experimental status. They are essentially overhead-free wrappers around the values of other types. Let’s try to rewrite the previous type alias example using inline classes:
inline class CustomersByDivisionWrapper(
val map: Map<Division, List<Customer>>)
class ProcessorInline {
fun processCustomers(customers: CustomersByDivisionWrapper) {
customers.map.forEach { entry ->
println(entry.key)
entry.value.forEach(::println)
}
}
}
And this is how you could call this method:
ProcessorInline().processCustomers(
CustomersByDivisionWrapper(mapOf(
Division("North")
to listOf(Customer("John"), Customer("Mary")),
Division("South")
to listOf(Customer("Fred"), Customer("Jill"))
)
))
Note three immediately visible differences from type aliases:
- the inline class not an alias, but a wrapper with a single property, representing the wrapped value;
- to access the wrapped value, you use its property name (in our case,
map) - to pass a wrapped object to the method accepting a wrapper, you have to instantiate the wrapper using its constructor; simply passing the value to the accepting method won’t work.
Now let’s look at the compiled ProcessorInline class:
public final class ProcessorInline {
public final void processCustomers-RBqTKbU(
Map<Division, ? extends List<? extends Customer>>);
public ProcessorInline();
}
Note that the type of the method arguments didn’t change — the method still accepts a Map, so there’s no wrapping overhead involved. However, note the method name — processCustomers-RBqTKbU. This is the so-called method mangling — any method accepting the inline class receives a unique name.
If we now add a method that accepts the original type (or any other inline class wrapping the same type, e.g. AnotherWrapper), there won’t be a compiler error, e.g. this works:
fun processCustomers(customers: CustomersByDivisionWrapper) { }
fun processCustomers(customers: AnotherWrapper) { }
fun processCustomers(customers: Map<Division, List<Customer>>) { }
Such method overloading is possible specifically thanks to the method name mangling. The decompiled code will now look like the following:
public final class ProcessorInline {
public final void processCustomers-sjwEFNk(
Map<Division, ? extends List<? extends Customer>>);
public final void processCustomers-bme9n3A(
Map<Division, ? extends List<? extends Customer>>);
public final void processCustomers(
Map<Division, ? extends List<Customer>>);
public ProcessorInline();
}
It’s worth saying, however, that in some cases the value still gets wrapped. You could have noticed that the CustomersByDivisionWrapper.class file was generated on compilation — specifically for this purpose.
Wrap-Up
Inline classes and type aliases provide somewhat similar features (they may be used as an alternative for a certain type while avoiding the overhead of creating a wrapper at runtime.
Type aliases may be substituted by the original types, but their declaration doesn’t create a new type. One of the consequences is that you could run into the clashing of methods that accept type aliases and original types.
Inline classes are not assignment-compatible with the wrapped values, but their declaration involves the creation of a new type and mangling of methods that accept those types, meaning the method name clashing won’t occur.