Type alias in Kotlin

Level 4210 keystrokes

typealias gives an existing type a shorter or more descriptive name; it does not create a new type. It works for generic types and function types too, as with Predicate<T>.

Kotlin code

// UserMap is just another name for Map<String, Int>
1typealias UserMap = Map<String, Int>
// A generic alias for a function type: takes a T and returns a Boolean
2typealias Predicate<T> = (T) -> Boolean
3
// Use the alias as the declared type; "to" builds each key-value pair
4val ages: UserMap = mapOf("Alice" to 25, "Bob" to 30)
// Predicate<Int> means (Int) -> Boolean, so it is an Int
5val isEven: Predicate<Int> = { it % 2 == 0 }
6
// mapOf keeps insertion order: prints {Alice=25, Bob=30}
7println(ages)
// Call the function value: 4 is even, so print true
8println(isEven(4))

Output

{Alice=25, Bob=30}
true
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • =× 6
  • (× 5
  • )× 5
  • "× 4
  • >× 4
  • <× 3
  • ,× 2
  • :× 2
  • -× 1
  • {× 1

More Kotlin examples at level 4

← Kotlin typing practice