我有一个scala类:
Rts.scala
class Rts(buffer:Iterator[Tse]) extends Ts
{ //Some methods}
现在我试图将Tse列表放在java类的上述类的构造函数中:
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
将列表放入构造函数的正确方法是什么?
答案 0 :(得分:1)
Scala的scala.collection.Iterator
与java.util.Iterator
的类型不同。另请参阅this question。
简而言之,以下内容应该有效:
new Rts(scala.collection.JavaConversions$.MODULE$.asScalaIterator(iterator));
(用于从Java调用对象的方法,see here)。
由于这非常难看,因此最好在Scala库中定义辅助Java API。例如:
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了解差异)。