34

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

5 Answers 5

48

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Picked this one as it answered my specific question more closely. The line I ended up with was: new CyclicIterator<ActorRef>((Seq<ActorRef>) asScalaBuffer(workers).toList());
as of 2024 the JavaConversion is deprecated, use the scala.jdk.CollectionConverters instead. See the related answer stackoverflow.com/questions/62081253/….
4

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

1 Comment

Thanks for the answer. I guess I was mistaking immutable.Seq for a concrete type!
3

You can try this:

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

Comments

1

You can use:

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

Comments

1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.