Kotlin Type Aliases

A type alias creates a new name for an existing type. It does not create a new type — it is just a shorthand. Type aliases improve readability when types are long, complex, or carry domain-specific meaning.

Defining a Type Alias

typealias Name = String
typealias Age = Int
typealias Score = Double

fun createProfile(name: Name, age: Age, score: Score): String {
    return "$name | Age: $age | Score: $score"
}

fun main() {
    println(createProfile("Alice", 30, 92.5))
}

The function signature reads more clearly. Name, Age, and Score tell you intent, while plain String and Int do not.

Type Aliases for Complex Types

typealias StringTransformer = (String) -> String
typealias UserMap = Map
typealias EventHandler = (event: String, data: Any?) -> Unit
typealias Matrix = Array

fun applyTransform(text: String, transform: StringTransformer): String = transform(text)

fun main() {
    val shout: StringTransformer = { it.uppercase() + "!" }
    val whisper: StringTransformer = { it.lowercase() }

    println(applyTransform("Hello", shout))    // HELLO!
    println(applyTransform("HELLO", whisper))  // hello
}

Type Alias for Generic Types

typealias StringList    = List
typealias IntPair       = Pair
typealias NamedValues   = Map

fun sumPair(p: IntPair) = p.first + p.second

fun printValues(values: NamedValues) {
    values.forEach { (name, value) -> println("$name = $value") }
}

fun main() {
    val p: IntPair = Pair(10, 20)
    println(sumPair(p))   // 30

    val readings: NamedValues = mapOf("temperature" to 36.5, "pressure" to 101.3)
    printValues(readings)
}

Type Aliases in Collections

typealias StudentId = Int
typealias GradeMap = MutableMap

fun addGrade(grades: GradeMap, studentId: StudentId, score: Double) {
    grades[studentId] = score
}

fun topStudents(grades: GradeMap): List =
    grades.filter { it.value >= 90.0 }.keys.toList()

fun main() {
    val grades: GradeMap = mutableMapOf()
    addGrade(grades, 101, 88.0)
    addGrade(grades, 102, 95.0)
    addGrade(grades, 103, 72.0)
    addGrade(grades, 104, 91.0)

    println("Top students: ${topStudents(grades)}")  // [102, 104]
}

Type Alias vs Real Type


typealias UserId = Int
typealias ProductId = Int

fun getUser(id: UserId) = "User $id"
fun getProduct(id: ProductId) = "Product $id"

val userId: UserId = 42
val productId: ProductId = 42

// Type aliases are just names — NOT separate types
// getUser(productId) works, even though intent was UserId
// For true separation, use inline value classes (different topic)

Function Type Aliases

typealias Validator = (T) -> Boolean
typealias Mapper = (A) -> B
typealias Predicate = (T) -> Boolean

fun  filter(list: List, predicate: Predicate): List =
    list.filter(predicate)

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

    val isEven: Predicate = { it % 2 == 0 }
    val isAboveFive: Predicate = { it > 5 }

    println(filter(numbers, isEven))       // [2, 4, 6, 8, 10]
    println(filter(numbers, isAboveFive))  // [6, 7, 8, 9, 10]
}

Practical Example: Event System

typealias EventName = String
typealias EventPayload = Map
typealias EventListener = (EventPayload) -> Unit
typealias ListenerMap = MutableMap>

object EventSystem {
    private val listeners: ListenerMap = mutableMapOf()

    fun on(event: EventName, listener: EventListener) {
        listeners.getOrPut(event) { mutableListOf() }.add(listener)
    }

    fun emit(event: EventName, payload: EventPayload) {
        listeners[event]?.forEach { it(payload) }
    }
}

fun main() {
    EventSystem.on("login") { payload ->
        println("User logged in: ${payload["username"]}")
    }

    EventSystem.emit("login", mapOf("username" to "alice", "ip" to "192.168.1.1"))
}

Output:

User logged in: alice

Leave a Comment

Your email address will not be published. Required fields are marked *