在Java中使用Scala 2.10.1值类型 [英] using Scala 2.10.1 Value Types in Java

查看:94
本文介绍了在Java中使用Scala 2.10.1值类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将2.9。*项目更新为2.10。我有几个基本类型(角度,长度等)的类,看起来它们是值类型的完美候选者。不幸的是,我使用这些类型的Java代码没有编译,我无法弄清楚原因。我把它简化为一组非常简单的代码。任何建议都将非常感激。

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. Unfortunately, my Java code that uses these types is not compiling, and I can't figure out why. I have simplified it down to a very simple set of code. Any suggestions would be much appreciated.

角度等级定义(scala)

package com.example.units

class Angle(val radians : Double) extends AnyVal
{
  def degrees = radians * 180.0 / math.Pi
}

object Angle
{
  val Zero = new Angle(0)
}

角度测试用例(用Java编写)

package com.example.units;

import junit.framework.Assert;
import org.junit.Test;

public class AngleTest
{
    @Test
    public static void TestZero()
    {
        Angle a = Angle.Zero();
        Assert.assertEquals(a.degrees(), 0, 1E-9);

    }

}

编译时,我收到此错误:

When I compile, I get this error:

AngleTest.java:19 incompatible types
found :double
required: com.example.units.Angle
Angle a = Angle.Zero();

            ^

在我看来,好像Angle.Zero被退回作为双重而非角度。我尝试添加box / unbox方法,但继续收到相同的错误。再次,非常感谢任何帮助。

It looks to me as if Angle.Zero is being returned as a double, not an Angle. I tried adding box/unbox methods, but continue to receive the same error. Again, any help would be greatly appreciated.

推荐答案

Scala编译器将值类转换为未装箱类型,从而消除了运行时的成本。检查已编译的类文件 Angle ,您将看到:

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();

因此,从Java的角度来看,Angle.Zero返回一个双精度数;它不知道Scala的值类的语义。

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自己的方法,例如 degrees ,被编译成a)一个静态扩展方法,它接受未装箱的值( double )b)实例方法:

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();

这意味着后者仍然可以在 Angle的实例上调用 in Java:

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);

这篇关于在Java中使用Scala 2.10.1值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆