Type Aliases in Kotlin

Suneet Agrawal
3 min readDec 23, 2018

--

Life is painful when you have two or more classes with the same name but different package name and you have to use them both in the same place.

This post was originally posted at https://agrawalsuneet.github.io/blogs/type-aliases-in-kotlin/ and reposted on Medium on 23rd Dec 2018.

Only one import can be added and the other one needs to be referenced by its complete package name dot class name. Every time you use the second class name, you need to use it by the entire package name of that class.

Kotlin has a better way to handle this case. It provides you type aliasing which basically provides an alternative name for the class.

typealias DemoCustomView =
com.agrawalsuneet.demoapp.common.customviews.View

In the above example, we aliased the View class which is in a specific package (“com.agrawalsuneet.demoapp.common.customviews”). Now we can directly use our View class using “DemoCustomView” and it will not conflict with android.view.View class.

val demoView = DemoCustomView(context)

the above code will do exactly the same as

val demoView = 
com.agrawalsuneet.demoapp.common.customviews.View(context)

You can define this typealias in any Kotlin file within the project but outside the class. You can not define the typealias inside any class as nested and local type aliases are not supported.

Most of the time, it’s useful to shrink collection types.

typealias MapIntToList = HashMap<Int, List<String>>

and use them directly as

val map = MapIntToList()

You can typealias to Template type also.

typealias MapIntToTemplate<T> = HashMap<Int, T>//and then to use itval stringMap = MapIntToTemplate<String>()
val mapOfLists = MapIntToTemplate<List<Int>>()

It’s useful to typealise the inner classes or interfaces.

class DemoClass {    interface ViewHolderCallback

inner class CustomViewHolder
}
typealias ViewHolderCallbackInner = com.agrawalsuneet.demoapp.common.DemoClass.ViewHolderCallback

typealias CustomViewHolderInner = com.agrawalsuneet.demoapp.common.DemoClass.CustomViewHolder

//another example
typealias AndroidColors = android.R.color
typealias ProjectColors = R.color
ContextCompat.getColor(this, ProjectColors.colorPrimary)
ContextCompat.getColor(this, AndroidColors.black)

You can even provide different aliases for function types.

typealias Conditional<T> = (T) -> Booleanval oddFilter: Conditional<Int> = { it % 2 == 1 }print(listOf(1, 2, 3, 4).filter(oddFilter))//orval fourDigitFilter : Conditional<String> = { it.length == 4}print(listOf("abc", "abcd", "abcde").filter(fourDigitFilter))

And we are done. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

Reference: Kotlin docs

--

--