What is type Alias in Kotlin?


#1

Guyz I have been struggling to understand the type alias in kotlin.
So can you guyz please tell me what is it means in Kotlin is it as same as Casting in java?

typealias NodeSet = Set<Network.Node>

typealias FileTable = MutableMap<K, MutableList>

typealias MyHandler = (Int, String, Any) -> Unit

typealias Predicate = (T) -> Boolean

I have previous experience in Java Only


#2

Type aliases provide alternative names for existing types. […] It’s useful to shorten long generic types
Source: https://kotlinlang.org/docs/reference/type-aliases.html

Just as its name implies, they are aliases you can use to refer to a type.
For example, this two pieces of code are equivalent:

fun isValid(predicate: (String) -> Boolean) {
    TODO("Something")
}
typealias Predicate = (String) -> Boolean

fun isValid(predicate: Predicate) {
    TODO("Something")
}

#3

Another way to think about type aliases is that they are like inline for types. If you use a type alias, it works by replacing all of you type aliases with the supplied type.

typealias MyInt = Int

val foo: MyInt = 4

is getting replaced by

val foo: Int = 4

#4

Thanks Really Helped me. :slight_smile:


#5

Got it thanks :slight_smile: