I use typealiases in my Kotlin code a lot, but I wonder if I can enforce type-safety on them.
typealias Latitude = Double
typealias Longitude = Double
fun someFun(lat: Latitude, lon: Longitude) {...}
val lat: Latitude = 12.34
val lon: Longitude = 56.78
someFun(lon, lat) // parameters are in a wrong order, but the code compiles fine
It would be nice if I could somehow prevent implicit casting between typealiases, helping to avoid such issues.
Of course, there is a problem, that the operations on basic types would be not available for typealiases, but it can be solved with extension functions (or casts).
I don't want to use data classes, holding a single field, because it seems a bit of overkill, especially for primitive types (or maybe I am wrong and they'll be optimized out?)
So the question: can I somehow enforce type-safety for typealiases?
Type aliases provide alternative names for existing types. If the type name is too long you can introduce a different shorter name and use the new one instead. It's useful to shorten long generic types.
Type parameter constraints allow you to limit the types that can be accepted as a type argument to an upper bound, giving you the ability to invoke functions and properties on an object while preserving the type.
A type alias allows you to provide a new name for an existing data type into your program. After a type alias is declared, the aliased name can be used instead of the existing type throughout the program. Type alias do not create new types. They simply provide a new name to an existing type.
Inline classes are already available as of Kotlin 1.3 and currently are marked as experimental. See the docs
Unfortunately you can't avoid this currently. There is a feature in progress - inline classes (#9 in this document), which will solve the problem with the runtime overhead, while enforcing compile time type-safety. It looks quite similar to Scala's value classes, which are handy if you have a lot of data, and normal case classes will be an overhead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With