Android Bites — 10: Type aliases

Ravikant Paudel
EKbana
Published in
2 min readJun 8, 2018

--

Type aliases provide alternative names for existing types. If the type name is too long then we can introduce a different shorter name or an “alias” and use it instead.

Type aliases do not introduce new types. They are equivalent to the corresponding underlying types.

class A {
inner class R{
init {
println("This is R of class A")
}
}
}
class B {
inner class R{
init {
println("This is R of class B")
}
}
}
typealias AInner = A.R
typealias BInner = B.R

In the above example, by utilizing Kotlin’s type alias, we can provide alternative names for inner class R of class A and B. As a result, now we can call R class of A by AInner and R class of B by BInner.

var x = AInner  //with typealias

If we do not use type alias then we have to import the class or call the inner class from its main class which may prove to be tedious and long. Thus, type alias helps to convert its name to something much more simpler and understandable.

var x = A.R     //without typealias

When we add typealias Predicate<T> and use Predicate<Int> in our code, the Kotlin compiler always expand it to (Int) -> Boolean. Thus we can pass a variable of our type whenever a general function type is required and vice versa:

typealias Predicate<T> = (T) -> Boolean

fun foo(p: Predicate<Int>) = p(42)

fun main(args: Array<String>) {
val f: (Int) -> Boolean = { it > 0 }
println(foo(f)) // prints "true"

val p: Predicate<Int> = { it > 0 }
println(listOf(1, -2).filter(p)) // prints "[1]"
}

Why to use typealias?

In real cases, usually when working with an app, it has its own function for handling special tasks such as getting data from api and sending data back, fetching and displaying data in the app and so on. This gives rise to verbose, long classes with inner functions which may be difficult to understand and thus implementing type alias helps.

Conclusion :

Type aliases are pretty useful in different cases. But, keep in mind that you should not overuse them and in some places it would be redundant to declare them.

Reference:

--

--