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) { … }
In this example we used AbsoluteXY
typealias to define that function draw
accept absolute coords instead of relative or something else.
Top comments (4)
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.
Have you also checked inline classes? Type safety + zero runtime overhead at the same time ;)
Unfortunatelly, they have several restrictions for now (like unavailable serialization via kotlinx.serialization) :)
Also, I planned to write about them a little bit later:)