typealias in Kotlin is a mechanism for declaring an alternative name for an existing type (class, interface, function, generic type, etc.). It is used for:
Limitations:
Example of usage:
typealias ClickHandler = (View, MotionEvent) -> Unit fun setClickHandler(handler: ClickHandler) { // ... } val handler: ClickHandler = { view, event -> // Logic handling }
Support and readability:
Question: "Are typealias in Kotlin new types from the compiler's perspective, and can they be used to restrict variable values?"
Answer: No, typealias is only a synonym for a type. They do not form a new type and do not provide any additional compile-time checks. All functions, variables, and parameters of typealias type are still the same original type.
Example:
typealias UserId = String typealias Email = String fun process(id: UserId) {} fun process(email: Email) {} process("abc@def.com") // No error — cannot differentiate!
Story
Used typealias for identifiers of different entities (UserId, OrderId), assumed the compiler would distinguish them, but in reality, passed values to each other without compile-time errors, leading to logic mixing and bugs.
Story
When migrating from an old API, assigned complex lambda expressions typealias, but did not specify new definitions in the documentation. The result — programmers did not understand what the alias meant (for example, Loader), and applied it incorrectly, resulting in runtime errors.
Story
In one of the projects, redefined typealias ViewClickHandler in different files with different signatures, thinking that aliases would be globally associated. As a result — during documentation auto-generation, duplication appeared, and a name conflict arose during compilation.