我有一个scala类:
Rts.scala
class Rts(buffer:Iterator[Tse]) extends Ts
{ //Some methods}现在,我试图从java类将Tse list放到上面类的构造函数中:
Tse tse1= new Tse(1285927200000L, 1285928100000L, 0.0);
Tse tse2 = new Tse(1285928100000L, 1285929000000L, 1.0);
Tse tse3= new Tse(1285929000000L, 1285929900000L, 2.0);
Tse tse4 = new Tse(1285929900000L, 1285930800000L, 3.0);
List<Tse> entryList = new ArrayList<Tse>();
entryList.add(tse1);
entryList.add(tse2);
entryList.add(tse3);
entryList.add(tse4);
Iterator<Tse> iterator = entryList.iterator();
Rts rts= new Rts(iterator); //compile time error错误摘要:
The constructor Rts(Iterator<Tse>) is undefined将列表放到构造函数中的正确方法是什么?
发布于 2016-01-07 11:04:37
Scala的scala.collection.Iterator与java.util.Iterator的类型不同。另见this question。
简言之,以下内容应该能奏效:
new Rts(scala.collection.JavaConversions$.MODULE$.asScalaIterator(iterator));(用于从Java调用对象的方法,see here)。
因为这很难看,所以最好在Scala库中定义一个辅助Java。例如:
class Rts(buffer: Iterator[Tse]) extends Ts {
// overloaded constructor that can be used from Java
def this(buffer: java.util.Iterator[Tse]) = this({
import scala.collection.JavaConverters._
buffer.asScala
})
}然后,呼叫应该直接工作:
new Rts(iterator);否则,迭代器只能使用一次。你确定这是你想要的吗?如果使用其他集合(如Seq或Iterable ),可能会更好。同样,您可以在JavaConverters和JavaConversions中找到与Java进行互操作的方法(请参阅here中的差异)。
https://stackoverflow.com/questions/34653178
复制相似问题