using Scala 2.10.1 Value Types in Java

前端 未结 1 2034
我寻月下人不归
我寻月下人不归 2021-01-17 19:56

I am updating my 2.9.* project to 2.10. I have several classes for fundamental types (angles, lengths, etc) that seem like they are perfect candidates for value types. Unf

相关标签:
1条回答
  • 2021-01-17 20:38

    Scala compiler turns value classes into their unboxed type, which eliminates their cost for runtime. Inspecting the compiled class file for Angle, you'll see:

    public static double Zero();
    

    So from Java's point of view, Angle.Zero returns a double; it's not aware of the semantics of Scala's value classes.

    Angle's own methods, such as degrees, get compiled into a) a static extension method that takes in the unboxed value (double) b) an instance method:

    public static double degrees$extension(double);
    public double degrees();
    

    Which means the latter can still be called on an instance of Angle in Java:

    Angle a = new Angle(0);
    Assert.assertEquals(a.degrees(), 0, 1E-9);
    
    0 讨论(0)
提交回复
热议问题