0
0
KotlinHow-ToBeginner · 3 min read

How to Use typealias in Kotlin: Simple Guide

In Kotlin, typealias lets you create a new name for an existing type to make code easier to read and write. You use it by writing typealias NewName = ExistingType, which helps especially with long or complex types.
📐

Syntax

The typealias keyword defines a new name for an existing type. The syntax is:

  • typealias NewName = ExistingType

Here, NewName is the new name you want to use, and ExistingType is any valid Kotlin type like a class, interface, or function type.

kotlin
typealias StringList = List<String>
💻

Example

This example shows how to use typealias to simplify a function type and a list type for better readability.

kotlin
typealias StringList = List<String>
typealias ClickHandler = (Int, String) -> Unit

fun handleClick(handler: ClickHandler) {
    handler(1, "Button clicked")
}

fun main() {
    val names: StringList = listOf("Alice", "Bob", "Carol")
    println("Names: $names")

    handleClick { id, message ->
        println("Clicked item id: $id with message: $message")
    }
}
Output
Names: [Alice, Bob, Carol] Clicked item id: 1 with message: Button clicked
⚠️

Common Pitfalls

One common mistake is thinking typealias creates a new type. It only creates a new name for an existing type, so it does not add type safety or create a distinct type.

Also, avoid using typealias for very simple types where it adds confusion instead of clarity.

kotlin
/* Wrong: expecting typealias to create a new type */
typealias UserId = Int

fun printId(id: UserId) {
    println(id)
}

fun main() {
    val id: Int = 123
    printId(id) // This works because UserId is just Int
}
Output
123
📊

Quick Reference

  • Purpose: Create readable names for existing types.
  • Syntax: typealias NewName = ExistingType
  • Use cases: Simplify long types, rename function types, improve code clarity.
  • Note: Does not create a new distinct type.

Key Takeaways

Use typealias to give a new name to an existing type for better readability.
It works well for complex types like function types or long generic types.
typealias does not create a new type, just a new name.
Avoid overusing typealias for simple types to keep code clear.
Use typealias to make your Kotlin code easier to understand and maintain.