5 ms·
> I find feelings about this depend a lot on how much ceremony the type system involves; and just how many units and references to them there are in the system.
by rowanajmarshall 5y ago
> I find feelings about this depend a lot on how much ceremony the type system involves; and just how many units and references to them there are in the system.
Ideally it'd be as simple as:
typealias Dollars = BigDecimal
typealias Cents = Long
that's valid Kotlin, but the equivalent is doable in most languages nowadays (Java being a big exception).
- dtech 5y agoI recommend against that, and use proper (wrapper) types. I don't know Kotlin, but in most languages if you alias 2 types to the same base type, for example Seconds and Minutes to Long, the compiler will happily allow you to mix all 3 of them, defeating the protection full types would bring.
- stefs 5y agothat's correct. typealiases are the wrong solution here. the better solution would be value classes, but of course, the unit shouldn't be the type.
- dragonwriter 5y ago> typealias Dollars = BigDecimal > typealias Cents = Long If I ever have to deal with monetary values in a program where someone thought this was a good idea, ... well, it really won't be the worst thing I’ve ever dealt with, but, still. (If you have dollars and cents as types in the same program, they darn well better work properly together, which is unlikely to work if they are both just aliases for basic numeric types.)
- stefs 5y agodon't do this! typealias Cents = Long typealias Meters = Long Cents(3) + Meters(4) = 7L that's exactly the thing we want to prevent. the classes shouldn't be for units at all, the type should represent the type of unit. so instead of a class Seconds you should have a class Duration, instead of class Meters you should have a type Distance. that's because the unit of the different types can be converted between each other. Dollars and Cents are a bit of a bad example because currencies can't be easily converted between each other, as conversion is dependent on many factors that change over time. meters, yards, feet, lightyears, miles, chain, furlongs, whatever describe a multiple of the same thing though, so a different type for each unit isn't necessary, as the input that was used to create the instance isn' usually needed. the counter example would be datetime with timezones - a datetime with a timezone convers a lot more information than the datetime converted to UTC.