Type aliases may be substituted by the original types, but their declaration doesn’t create a new type. Inline classes and type aliases provide somewhat similar features (they may be used as an alternative for a certain type while avoiding the overhead of creating a wrapper at runtime. You could have noticed that the CustomersByDivisionWrapper.class file was generated on compilation - specifically for this purpose. It’s worth saying, however, that in some cases the value still gets wrapped. Suppose we have two classes, Customer and Division, and we need to implement some processing of customers grouped by division: data class Customer(val name: String) data class Division(val name: String) typealias CustomersByDivisionMap = Map> class Processor Let’s apply type alias to make a complex generic type more readable. This example is probably not very useful. This declaration doesn’t create a new type, and you can pass the aliased type wherever the alias is expected (something that’s called assignment compatibility): typealias Str = String val s: Str = "Hello" They effectively allow you to declare a new name for any existing type. Type aliases first appeared in Kotlin version 1.1. You could use them to improve code clarity and type safety, but what’s the difference between them? This is the topic of this article. Those are inline classes and type aliases. The Kotlin programming language has two distinct features that may be used for similar purposes.
0 Comments
Leave a Reply. |