DEV Community

InsanusMokrassar
InsanusMokrassar

Posted on

Kotlin Typealiases

Hi! As a developer on Kotlin, I usually use typealias functionality and I wish to share my experience with you :)

What is it?

Typealiases (like inline classes) are the types which will be erased in runtime, but are available in coding. Compiler will use their type value to put on places in code where this typealias are called.

Advantages

  • Defining of types meaning
  • Zero-cost in runtime

Disadvantages

(Almost) absent typecheck. If you will use opposite by meaning and equal by type typaliases, compiler will not stop you

Example

typealias XY = Pair<Float, Float>
typealias AbsoluteXY = XY

…

fun draw(xy: AbsoluteXY) { … }
Enter fullscreen mode Exit fullscreen mode

In this example we used AbsoluteXY typealias to define that function draw accept absolute coords instead of relative or something else.

Top comments (4)

Collapse
 
jillesvangurp profile image
Jilles van Gurp

One useful feature with type aliases is that they support extension functions as well.

An alias does not introduce a new type; for the compiler it is equivalent to using the aliased type. So, it does check the type but just not that you use the alias consistently.

Collapse
 
alxgrk profile image
Alexander Girke

Have you also checked inline classes? Type safety + zero runtime overhead at the same time ;)

Collapse
 
insanusmokrassar profile image
InsanusMokrassar

Unfortunatelly, they have several restrictions for now (like unavailable serialization via kotlinx.serialization) :)

Collapse
 
insanusmokrassar profile image
InsanusMokrassar

Also, I planned to write about them a little bit later:)