Skip to content
Related Articles

Related Articles

Improve Article

Type Aliases vs Inline Classes

  • Last Updated : 19 Sep, 2019

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.

Type Aliases

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.gfgpractie.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 –

// here we define a type alias named key_values
// which will take two parameters int and string
typealias Key_values = Pair<Int, String>
fun main() {
    // we are setting two games but we don't
    // have to define Pair each time while using it
    val game1 = Key_values( 1, "Cricket")
    //instead we can directly use our type alias Key_values.
    val game2 = Key_values(2, "Football")


(1, Cricket)
(2, Football)

Inline Classes

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 –

interface Print {
    fun geekPrint(): String
inline class Value(val s: String) : Print {
    override fun geekPrint(): String = "Hello $s!"
fun main() {
    val name = Value("World")


Hello World!

My Personal Notes arrow_drop_up
Recommended Articles
Page :