Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Strongly-typed units and unit literals (e.g. 3mL, 10gal, 15m / 3s = 5m/s)

AFAIK F# has these and that's about it



I see this in some Rust crates, as you can implement traits for built-in, primitive types.

For instance, the `embedded_time` crate lets you do

    200.microseconds()
    5.Hz()
https://docs.rs/embedded-time/latest/embedded_time/


They can be implemented as a library C++ thanks to templates and user-defined literals, and there's a proposal to add them to stdlib based on one of the existing implementations: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p19...


You can implement it in C# too with zero run time cost.


I don't see how, except for manually rolling a struct for every new combination of units. The C# generic system is not flexible enough to define things like "m / s / s = (m/s^2)".


There's a Java compiler extension, Manifold[1], that adds this to Java.

[1] https://github.com/manifold-systems/manifold/tree/master/man...


You can make that in Kotlin, e.g.: `3.mph` or `(-45..45).deg` for ranges.

with definition like:

    val Double.mph: Speed
      get() = Speed.mph(this)

    data class Speed(val ms: Double)
      companion object {
        fun mph(mph: Double) = Speed(mph * 1609.344 / 3600.0)
      }


Frink (which OP mentions for its datetime syntax) has the concept of units and unit conversions built into the core language - but that's about all it does! I'd love to have this feature in a general-purpose language.





Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: