TypeAlias in Kotlin
Siddhant Mishra
Senior Android Developer at Teachmint | Kotlin and Java | DSA - 300+ on Leetcode | I read and write about Android and DSA
Today I will be writing about TypeAlias in Kotlin and how do I understand and use it in my day to day coding.
Typealias in Kotlin is just a convenient and easy way to represent longer data types which might be frustrating otherwise to write at several places in the code. TypeAlias helps us define a short hand notation to represent the datatypes which once defined helps us use it as a placeholder for the data type for which it is defined.
I would be correlating this concept with the macro concept in C++ which we heavily use. Take a look at this code -
Here I have defined pb to be push_back() and vvi to be vector<vector<int>>, now if you have used them, then you must be knowing how much it helps us in writing concise code. And you can also check out the way I have used those macros in the subsequent code. TypeAlias performs a similar thing, now take a look at the below code -
Now in the above code, instead of writing the higher order function everytime as (Int) -> Int, we can define it using typeAlias and use it using the shortend name.
At the byte code level, there is no trace of TypeAlias, the JVM converts the shortend names into their original forms at the compile time and removes the TypeAlias keyword conveniently.
Do use TypeAlias in your day to day coding and reap its benefits. Happy coding.