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.
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 it
val 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) -> Boolean
val oddFilter: Conditional<Int> = { it % 2 == 1 }
print(listOf(1, 2, 3, 4).filter(oddFilter))
//or
val fourDigitFilter : Conditional<String> = { it.length == 4}
print(listOf("abc", "abcd", "abcde").filter(fourDigitFilter))