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>
  2. typealias FileTable<K> = MutableMap<K, MutableList<File>>

You can provide different aliases for function types:

  1. typealias MyHandler = (Int, String, Any) -> Unit
  2. 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. }
  7. typealias AInner = A.Inner
  8. 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
  2. fun foo(p: Predicate<Int>) = p(42)
  3. fun main() {
  4. val f: (Int) -> Boolean = { it > 0 }
  5. println(foo(f)) // prints "true"
  6. val p: Predicate<Int> = { it > 0 }
  7. println(listOf(1, -2).filter(p)) // prints "[1]"
  8. }