Mobile Development
Kotlin
Subjective
Oct 04, 2025
What are type aliases and when should you use them?
Detailed Explanation
Type aliases create alternative names for existing types, improving code readability and maintainability.\n\n**Basic type aliases:**\n\ntypealias UserId = Int\ntypealias UserName = String\ntypealias EmailAddress = String\n\nfun createUser(id: UserId, name: UserName, email: EmailAddress) {\n // Implementation\n}\n\n// Usage\nval userId: UserId = 123\nval userName: UserName = "John Doe"\nval email: EmailAddress = "john@example.com"\n\n\n**Function type aliases:**\n\ntypealias EventHandler = (String) -> Unit\ntypealias Predicate = (T) -> Boolean\ntypealias Transformer = (T) -> R\n\nclass EventManager {\n private val handlers = mutableListOf()\n \n fun addHandler(handler: EventHandler) {\n handlers.add(handler)\n }\n \n fun fireEvent(event: String) {\n handlers.forEach { it(event) }\n }\n}\n\n// Usage\nval logger: EventHandler = { event -> println("Log: $event") }\nval emailer: EventHandler = { event -> sendEmail(event) }\n\n\n**Generic type aliases:**\n\ntypealias StringMap = Map\ntypealias MutableStringMap = MutableMap\ntypealias NodeList = List>\n\n// Usage\nval userPreferences: StringMap = mapOf(\n "theme" to "dark",\n "language" to "en"\n)\n\nval cache: MutableStringMap = mutableMapOf()\n\n\n**Complex type aliases:**\n\ntypealias ApiResponse = Result\ntypealias ValidationResult = Either
- , ValidatedData>\ntypealias DatabaseConnection = Connection\n\n// Nested generics\ntypealias UserRepository = Repository
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts