Shorten Long Type Names with Kotlin Type Aliases

Type Aliasing is one of the many features of the Kotlin programming language. It allows you to give an alternative name to a type.

typealias WordList = List<String>

The official Kotlin docs suggests using Type Aliases for long generic types

typealias Room = Pair<String, List<User>>
typealias FileTable<K> = MutableMap<K, MutableList<File>>

Or Function types

typealias MyHandler = (Int, String, Any) -> Unit

Or Inner and Nested Classes

class A {
    inner class Inner
class B {
    inner class Inner

typealias AInner = A.Inner
typealias BInner = B.Inner

Type aliases don’t introduce any new types. The Kotlin compiler will always compile them as their original types.

Other Uses of Type Aliases

If you have 2 classes with the same name but different packages and you want to use them both in the same class, Type Aliases can help immensely.

This is especially the case while we’re in the shift to AndroidX. For example:

val legacyFragment = Fragment()
val androidXFragment =

In the code above, we can declare the old legacy Android Fragment as a simple Fragment(). However, since a Fragment() has already been declared, we have to give the AndroidX Fragment its full name when we refer to it.

typealias LegacyFragment = Fragment
typealias XFragment =

val legacyFragment = LegacyFragment()
val androidXFragment = XFragment()

Instead, we can use Type Aliasing to make our code much more readable and concise.

Not to be confused with Inline Classes

It might seem that Type Aliases are very similar with Inline Classes which provide a wrapper around a single class by containing that class as a single property.

The main difference with Type Aliases and Inline Classes is that Inline Classes introduce a new type to the compiler. Type Aliases simply provide an alternative name to existing classes.

This means that Inline Classes provide additional heap overhead than Type Aliases. They do however come with their own set of advantages. More on Inline Classes another day.