Kotlin typealias

Type alias allows you to create an alias for any Type.  Why would we want to create another name for Int or String?  Its all about readability  Consider that you are storing a time, or a currency amount?  In java days we would store them:

String amount = 250
Int elapsedTime = 120

How do we know if that amount is mean to represent cents or dollars? Does that time represent 2 minutes, 2 hours or 120ms?  We can make this a lot more readable in kotlin with the use of typealias

typealias Cents = Int
fun Cents.asDollars(): Float = this.toFloat()/100
typealias Seconds = Int
fun Seconds.asMinutes(): Float = this.toFloat()/60
amount: Cents = 250
elapsedTime: Seconds = 120

Now it is really readable, the amount is 250c or asDollars() 2.50 and the time is 120 seconds to asMinutes(), 2.

Underneath the hood, the compiler treats all these as Ints, so there is no performance issues, but readability is greatly improved.

Leave a Reply