What is type Alias in Kotlin?

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

1 Like

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")
}
1 Like

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

Thanks Really Helped me. :slight_smile:

Got it thanks :slight_smile:

What is the difference between inline and typealias then? Can we use inline instead.

For starters inline classes can have their own members (functions and properties). Unlike typealiases, they are not assignment compatible with their underlying type.

1 Like