typealias in Kotlin

AshuOnline Forall
2 min readMar 6, 2021

One of the cool feature of Kotlin programming language to improve code readability is a feature called “typealias”. Let us see the simple function code below which prints a table of a number, which is passed as an argument to it.

fun printTable(number: Int) {
for (i in 1..10) {
println("$number x $i = " + i * number)
}
}

Here, the type of the “number” is an Int. Instead of using this built-in type for function parameter, we can create a simple “alias” — another “name” of our choice and tell Kotlin to treat it as Int.

typealias Number = Int

Now, we this above change, we can use Number as equivalant to Int in our Kotlin code. And hence the above simple program to print the table can be modified to use “typealias” which we created.

fun printTable(number: Number) {
for (i in 1..10) {
println("$number x $i = " + i * number)
}
}

The Kotlin compiler will know that it has to treat Number as Int because we have created the “typealias” for it.

You may ask : Why on earth I would use Number for a replacement for Int?

Well, the answer is these typealias feature gives more contextual depth to your data types which makes more sense to your code.

Remember, one of the key Kotlin language feature is it makes code more “expressive” and by using typealias your code becomes more readable for you and your team members. The type “Number” may mean more meaningful to you and your team in the given context than Int — for example.

Also, 1 more technical point worth mentioning about “typealias” is it does not add new type, it simply allow you to use another name to existing type.

--

--