0
0
KotlinConceptBeginner · 3 min read

What is Type Alias in Kotlin: Simple Explanation and Examples

In Kotlin, a typealias lets you create a new name for an existing type to make code easier to read and understand. It does not create a new type but acts like a nickname for a complex or long type.
⚙️

How It Works

Think of typealias as giving a nickname to a long or complicated type name. Instead of writing the full type every time, you use the nickname to keep your code clean and simple. This is like calling a friend by a short name instead of their full name.

For example, if you have a complex type like a function type or a long generic type, you can create a typealias to make it easier to use. The compiler treats the alias exactly like the original type, so there is no extra cost or new type created.

💻

Example

This example shows how to create a type alias for a function type and use it in code.
kotlin
typealias ClickHandler = (Int, String) -> Unit

fun handleClick(click: ClickHandler) {
    click(10, "Button clicked")
}

fun main() {
    val myClick: ClickHandler = { id, message ->
        println("Clicked item id: $id with message: $message")
    }
    handleClick(myClick)
}
Output
Clicked item id: 10 with message: Button clicked
🎯

When to Use

Use typealias when you want to simplify complex type names or make your code more readable. It is especially helpful for long function types, nested generics, or when you want to give a meaningful name to a type.

For example, if you work with callbacks or listeners often, a type alias can make your code easier to understand and maintain. It also helps when you want to change the underlying type later without changing all the code that uses it.

Key Points

  • Type alias creates a new name for an existing type without creating a new type.
  • It improves code readability by shortening long or complex type names.
  • It is useful for function types, generics, and callback signatures.
  • The compiler treats the alias exactly like the original type.

Key Takeaways

Type alias in Kotlin gives a new name to an existing type to simplify code.
It does not create a new type but acts as a nickname for readability.
Use it to shorten complex types like function types or generics.
It helps maintain code by allowing easy type name changes.
The compiler treats the alias exactly like the original type.