Part 13 / Topic 6 of 7
Type aliases
A typealias gives an existing type a second, more readable name. It creates no new type
and costs nothing at runtime -- the compiler simply substitutes the real type back in wherever
the alias is used.
typealias ProductId = String
typealias PriceInRupees = Double
typealias Catalog = Map<ProductId, PriceInRupees>
typealias Validator<T> = (T) -> Boolean
fun <T> firstInvalid(items: List<T>, isValid: Validator<T>): T? = items.firstOrNull { !isValid(it) }
fun priceLookup(catalog: Catalog, id: ProductId): PriceInRupees? = catalog[id]
val catalog: Catalog = mapOf("P-01" to 420.0, "P-02" to 180.0, "P-03" to 210.0)
println("Price of P-02: ₹${priceLookup(catalog, "P-02")}")
println("Price of P-99: ${priceLookup(catalog, "P-99")}")
val prices = listOf(420.0, 180.0, -50.0, 210.0)
val positivePrice: Validator<Double> = { price -> price > 0 }
println("First invalid price: ${firstInvalid(prices, positivePrice)}")
Price of P-02: ₹180.0
Price of P-99: null
First invalid price: -50.0
Catalog reads better than Map<String, Double> at every call site, and ProductId/
PriceInRupees document what the String/Double actually mean -- without creating a real
wrapper type (and the allocation and equals/hashCode boilerplate that would come with one).
A typealias also works on a function type, which is the only way to give a repeated lambda
signature like (T) -> Boolean a name of its own.
Full program: examples/06_type_aliases.kt.
Done here? The practice set for Part 13 — including the solutions — is on the part page.