32

I'm trying to get Akka going in my Java project, and I'm hung up on a small issue with the Seq type(s) from Scala. I'm able to convert my Java List of ActorRef into a scala.collection.Seq, but the Akka API I'm trying to use requires a scala.collection.immutable.Seq. How can I make one?

Code:

static class Router extends UntypedLoadBalancer {
    private final InfiniteIterator<ActorRef> workers;

    public Router(List<ActorRef> workers) {
        Seq workerSeq = asScalaBuffer(workers);

        // how to get from the scala.collection.Seq above to the instance of
        // scala.collection.immutable.Seq required by CyclicIterator below?
        this.workers = new CyclicIterator<ActorRef>();
    }

    public InfiniteIterator<ActorRef> seq() {
        return workers;
    }
}
spieden
  • 1,239
  • 1
  • 10
  • 23

5 Answers5

47

You can use scala.collection.JavaConversions.asScalaBuffer to convert the Java List to a Scala Buffer, which has a toList method, and a Scala List is a collection.immutable.Seq.

Landei
  • 54,104
  • 13
  • 100
  • 195
  • Picked this one as it answered my specific question more closely. The line I ended up with was: new CyclicIterator((Seq) asScalaBuffer(workers).toList()); – spieden Jul 22 '11 at 17:42
4

The akka Java documentation for routers as well as the ScalaDoc for CyclicIterator both suggest that the CyclicIterator constructor takes a List.

Emil Sit
  • 22,894
  • 7
  • 53
  • 75
3

You can try this:

scala.collection.JavaConverters.asScalaIteratorConverter(list.iterator()).asScala().toSeq();
Dino
  • 7,779
  • 12
  • 46
  • 85
markus
  • 2,955
  • 2
  • 20
  • 13
1

You can use:

scala.collection.JavaConverters.collectionAsScalaIterableConverter(workers).asScala().toSeq()

Ben McCann
  • 18,548
  • 25
  • 83
  • 101
0

Since scala 2.12.0 JavaConversions is marked deprecated

@deprecated("use JavaConverters", since="2.12.0")
object JavaConversions extends WrapAsScala with WrapAsJava

so one should use JavaConverters

scala.collection.JavaConverters.asScalaIteratorConverter(list.iterator()).asScala().toSeq();

or idiomatically

scala.collection.JavaConverters.asScalaIterator(list.iterator()).toSeq();
dswiecki
  • 138
  • 2
  • 11