Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin type-safe typealiases

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?

like image 756
ekaerovets Avatar asked Apr 25 '18 17:04

ekaerovets


People also ask

What is type alias Kotlin?

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.

What is type parameters in Kotlin?

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.

What is type alias?

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.


1 Answers

Update for Kotlin 1.3

Inline classes are already available as of Kotlin 1.3 and currently are marked as experimental. See the docs

Original answer

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.

like image 72
Daniel Alexandrov Avatar answered Sep 30 '22 19:09

Daniel Alexandrov