1. Overview

In this quick tutorial, we’re going to get familiar with type aliases in Kotlin and their use cases. Along the way, we’ll also see how this feature manifests itself at the bytecode level.

2. Type Alias

In Kotlin, it’s possible to declare alternative names for existing types using type aliases. Let’s look at the basic syntax:

typealias <NewName> = <ExistingType>

These aliases can be useful in some scenarios. For instance, we can use them to attach more context to an otherwise general type:

typealias CreditCard = String
fun linkCard(card: CreditCard) {
    // omitted
}

As shown above, by defining a type alias for a String, we’re conveying more information and context to the caller.

Using type aliases is simple:

val cc: CreditCard = "1234****"
linkCard(cc)

Here, we’re assigning a String literal to a variable of type CreditCard. Moreover, we can perform String operations on CreditCard instances, too:

val other = cc.toUpperCase()

In addition to that, we can use Strings wherever CreditCard instances are expected:

linkCard("1234****")

Even though the linkCard function expects a CreditCard instance, we’re passing a String instance to it.

There are other use cases for type aliases, too. For instance, we may use them to create a new type with a more meaningful name for a function literal:

class HttpRequest
class HttpResponse
typealias RequestHandler = (HttpRequest) -> HttpResponse

Here, instead of defining web controllers as a function of HttpRequest -> HttpResponse, we’ll just use the RequestHandler type.

Here’s a more familiar example from Java 8 — declaring generic type aliases:

typealias Predicate<T> = (T) -> Boolean

Moreover, we can use type aliases to shorten some long data type names:

typealias Completed = CompletableFuture<Map<String, Pair<String, Int>>>

3. Bytecode Representation

Type aliases are merely artifacts of the source code. Therefore, they’re not introducing any new types at runtime. For instance, every place where we’re using a CreditCard instance, the Kotlin compiler translates it to a String.

To verify that this translation happens, we’ll take a look at the generated bytecode.

First, let’s compile the Kotlin code via kotlinc:

$ kotlinc TypeAlias.kt

Then, we can take a peek the generated bytecode via javap:

$ javap -c -p com.baeldung.alias.TypeAliasKt
Compiled from "TypeAlias.kt"
public final class com.baeldung.alias.TypeAliasKt {
  public static final void linkCard(java.lang.String);
  // truncated
}

As we can see, the linkCard method accepts a String instead of the declared type alias. So, as mentioned earlier, the Kotlin compiler erases the type aliases at compile-time and uses the underlying types at runtime.

4. Conclusion

In this short tutorial, we saw how and when to use type aliases in Kotlin. Then, we took a peek at the bytecode representation of this feature.

As usual, all the examples are available over on GitHub.

guest
0 Comments
Inline Feedbacks
View all comments