Efficient relabelled/custom basic types?


#1

I am working on a Java codebase which has a bunch of methods that return integers in various kinds of units, with little rhyme or reason to the selection. Now there have been a bunch of annoying bugs caused by me losing track of whether a Long is representing bytes, kilobytes, etc especially when they're parameters of futures and thus the context is missing.

This is my own fault, I could have cleaned this stuff up but haven’t. Anyway, it reminded me that often I really want to define my own units and casts between them, but otherwise have usage of them be as efficient as regular scalar types. so I could create a new type that works exactly the same as Integer but is not Integer, and would require explicit conversion to convert to something else:

val a : Seconds = 60;
var b: Minutes = a as Minutes;   // b == 1

Is there a convenient/efficient way to do this in Kotlin?


#2

In first versions of Kotlin you can do it only by creating wrappers, which will have memory and execution time overhead. Implementing it without runtime overhead requires some sort of type annotations, which won't be available in Kotlin 1.0. We may support it in later versions.

Anyway, if you are okay with runtime overhead, Kotlin features make it possible to make syntax conciser than Java, e.g.:

val a = 60.seconds
var b = a.toMinutes()


#3

That would be really nice to have. Or conversion from Liters to Gallons, Kilograms to Ounces,… Methods could be much more expressive.