Type aliases
Type aliases provide alternative names for existing types. If the type name is too long you can introduce a different shorter name and use the new one instead.
It’s useful to shorten long generic types. For instance, it’s often tempting to shrink collection types:
1. typealias NodeSet = Set<Network.Node>
3. typealias FileTable<K> = MutableMap<K, MutableList<File>>
You can provide different aliases for function types:
1. typealias MyHandler = (Int, String, Any) -> Unit
3. typealias Predicate<T> = (T) -> Boolean
You can have new names for inner and nested classes:
1. class A {
2. inner class Inner
3. }
4. class B {
5. inner class Inner
6. }
8. typealias AInner = A.Inner
9. typealias BInner = B.Inner
Type aliases do not introduce new types. They are equivalent to the corresponding underlying types. When you add typealias Predicate<T> and use Predicate<Int> in your code, the Kotlin compiler always expands it to (Int) -> Boolean. Thus you can pass a variable of your type whenever a general function type is required and vice versa:
1. typealias Predicate<T> = (T) -> Boolean
3. fun foo(p: Predicate<Int>) = p(42)
5. fun main() {
6. val f: (Int) -> Boolean = { it > 0 }
7. println(foo(f)) // prints "true"
9. val p: Predicate<Int> = { it > 0 }
10. println(listOf(1, -2).filter(p)) // prints "[1]"
11. }
