Kotlin Types Aliases

Imagine you are creating a project where you defined two classes with same name but different packages and you have to use them at once. Generally, you need to use whole package name dot class name format for the second one. For example, we have a class named ‘courses’ one in “com.gfg.apps” package and another in “com.gfg_practice.apps”, we can use one out of them using simple import and if we want to use second one we have to use full package name like “com.gfg_practie.apps.courses”.

In Kotlin, we have a solution for this named as Type aliases. Type aliases provide an alternate name for the existing types (in our case it is a class).

In our above scenario, we can do:

typealias course = com.gfg_practie.apps.courses 

and use the class courses from package “com.gfg_practice.apps” anywhere we want without defining the longer version of it every time we use it.

Kotlin program to demonstrate type aliases –



filter_none

edit
close

play_arrow

link
brightness_4
code

// here we define a type alias named Login_details
// which will take two strings as parameters
typealias Login_detials = Pair <String, String>
fun main() {
    // we are setting two users but we don't
    // have to define Pair each time while using it
    val my_details = Login_detials("Username1", "Password1")
    //instead we can directly use our type alias Credentials.
    val my_details2 = Login_detials("Username2", "Password2")
  
    println(my_details)
    println(my_details2)
}

chevron_right


Output:

(Username1, Password1)
(Username2, Password2)

Kotlin program to demonstrate –

filter_none

edit
close

play_arrow

link
brightness_4
code

typealias Number<T> = (T) -> Boolean
// defined a type alias named Number,  > is used as a separator here
  
fun main() {
    //it is used to loop through each element of the below list
    val x: Number<Int> = { it > 0 }
    //filter method only print those element which 
    // satisfies the condition (numbers > 0)
    println("Positive numbers in the list are: "
            +listOf(11, -1, 10, -25, 55 , 43, -7).filter(x))
  
}

chevron_right


Output:

Positive numbers in the list are: [11, 10, 55, 43]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.