Type Aliases vs Inline Classes
Kotlin is a programming language which brings all the powers of modern programming languages to android development. In this article, we will discuss about it’s two cool features namely Type Aliases and Inline Classes.
Let’s suppose you are creating a project where you defined two classes with same name but different packages.In need, you need to use whole package name dot class name format for the second one. For instance you have a class named ‘geek’ one in “com.gfg.apps” package and another in “com.gfgpractice.apps”, you can use one out of them using simple import and if you want to use second one you have to use full package name like “com.gfgpractice.apps.geek”.
Here, Type Aliases comes into the picture, type aliases provides a method to define an alternate name for our complex or too long class name. Type aliases do not introduce new types. They are same as the corresponding underlying types.
In our above scenario, we can do:
typealias geek = com.gfg.apps.geek
and use the name geek instead of “com.gfg.apps.geek” anywhere we want without defining the longer version of it every time we use it.
Kotlin example to demonstrate type aliases –
(1, Cricket) (2, Football)
Inline classes add the features of TypeAliases with value range of primitive data types. In some situations it is needed to create a wrapper around a specific type which will result in additional heap allocation during to runtime. To solve this issue, concept of inline classes is introduced. In this concept, data of the class is “inlined” into its usages.
Note: Inline classes introduce a truly new type, contrary to type aliases which only introduce an alternative name (alias) for an existing type.
Kotlin program to demonstrate inline class –
Please Login to comment...