Kotlin typealias Operator Tutorial

In this section we will learn what the typealias operator is and how to use it in Kotlin.

What is typealias operator in Kotlin?

The typealias operator is used to create alias names for data types in Kotlin. This alias name then represents the actual data type and could be used anywhere in the program that the original data type supposed to be used.

This is especially useful when it comes to function types (the data type we set for variables or parameters that hold lambda expressions).

Because if you think about it, the length of these data types can sometimes become really lengthy! So if we need to put this data type in multiple places of a source code, that can become a tedious task quickly!

Now, using the typealias operator, we can create a short alias name for a data type (specially a length data type) and then use that alias name wherever the main data type is needed.

Note: when a data type has an alias name, still that original name of the data type could be used in the program as well!

Kotlin typealias Syntax:

typealia AliasName = data-type

The name that comes after the typealias keyword is the alias name that we want to set for the target data type!

Also, the data type that we put after the assignment operator is the type that we want to create an alias name for it.

Example: using the typealias operator in Kotlin

typealias Converter = (Double)->Int 

fun main(){
    changeType(433.54){it.toInt()}
}

fun changeType(value:Double,convert:Converter){
    var res = convert(value)

    println("The result is: $res")
}

Output:

The result is: 433

How does typealias work in Kotlin?

Here, we have created an alias name for the function type (Double)→Int with the name Converter. This means now we can use the Converter name instead of this function type anywhere in the program that needs the data type.

For example, here we’ve passed this alias name as the data type for the convert parameter of the changeType function.

Now when calling this function, we need to pass a lambda expression that takes one Double argument and returns an integer value as a result.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies