2017-06-02 105 views
0

我有像编译好的java代码。将java转换为scala - 重载的静态方法

import org.jaitools.numeric.Range; 
Range<Integer> r1 = Range.create(1, true, 4, true); 

转换为斯卡拉像

val r1: org.jaitools.numeric.Range[Integer] = org.jaitools.numeric.Range.create(1, true, 4, true) 

编译为Java的似乎跟这个方法失败:

public static <T extends Number & Comparable> Range<T> create(T minValue, boolean minIncluded, T maxValue, boolean maxIncluded) { 
     return new Range<T>(minValue, minIncluded, maxValue, maxIncluded); 
    } 

而Scala编译器会选择使用

public static <T extends Number & Comparable> Range<T> create(T value, int... inf) { 
     return new Range<T>(value, inf); 
} 

即类型参数 不匹配。

两者都是在同一个类中重载的方法。 我怎样才能让Scala编译器选择正确的方法?

编辑

val r1: org.jaitools.numeric.Range[Integer] = org.jaitools.numeric.Range.create(1, true, 4, true) 

结果

overloaded method value create with alternatives: 
    [T <: Number with Comparable[_]](x$1: T, x$2: Int*)org.jaitools.numeric.Range[T] <and> 
    [T <: Number with Comparable[_]](x$1: T, x$2: Boolean, x$3: T, x$4: Boolean)org.jaitools.numeric.Range[T] 
cannot be applied to (Int, Boolean, Int, Boolean) 
     val r1: org.jaitools.numeric.Range[Integer] = org.jaitools.numeric.Range.create(1, true, 4, true) 

也许这也是convert java to scala code - change of method signatures其中的Java和Scala的类型系统不能很好地协同工作的情况下?

+0

我不熟悉这个特定的软件包,但是这似乎是类型转换的问题。尝试做Range.create(int2Int(1),true,int2Int(4),true); –

+0

你用'int2Int'指的是哪一种方法? –

+0

请注意,您正在使用引用java.util.Integer的Range [Integer],但是在scala中1和4是Int。 scala predef包含一个函数int2Int来完成转换。虽然这通常会自动发生,但在某些情况下可能会失败。这可能是其中之一 –

回答

2

你的问题是Intjava.lang.Integer是两个不同的东西。 create预计其第一个和第三个参数与type参数的类型相同。您将参数指定为Integer,但您传入的参数 - 1和4 - 类型为Int

您不能创建Range[Int],因为类型参数需要扩展NumberComparable,而Int则不需要。所以,你必须来包装你Int s转换Integer明确

val r1 = org.jaitools.numeric.Range.create(Integer.valueOf(1), true, Integer.valueOf(4), true)