0

I have a scala class:

Rts.scala

class Rts(buffer:Iterator[Tse]) extends Ts
{ //Some methods}

Now I am trying to put Tse list to the constructor of the above class from java class:

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

Error Summary:

The constructor Rts(Iterator<Tse>) is undefined

What is the right way to put the list to the constructor?

0__
  • 66,707
  • 21
  • 171
  • 266
sjain
  • 23,126
  • 28
  • 107
  • 185

1 Answers1

1

Scala's scala.collection.Iterator is not the same type as java.util.Iterator. See also this question.

In short, something like the following should work:

new Rts(scala.collection.JavaConversions$.MODULE$.asScalaIterator(iterator));

(for calling methods on objects from Java, see here).

Since this is quite ugly, it's better to define an auxiliary Java API in your Scala library instead. For example:

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

And then the call should work directly:

new Rts(iterator);

Otherwise, an iterator can only be used once. Are you sure that's what you want? Probably it would be better if you used another collection such as Seq or Iterable. Again you can find ways to interop with Java in JavaConverters and JavaConversions (see here for the difference).

0__
  • 66,707
  • 21
  • 171
  • 266
  • You can use scala.collection.JavaConversions.asScalaIterator which is marginally less ugly. – bdew Feb 01 '16 at 12:17