Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a scala.collection.immutable.Seq from a Java List in Java?

Tags:

java

scala

akka

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;     } } 
like image 286
spieden Avatar asked Jul 22 '11 00:07

spieden


People also ask

Can I use Java list in Scala?

A java list can be returned from a Scala program by writing a user defined method of Java in Scala.

Is Scala seq immutable?

Seq . The 2.13 default Seq is specifically immutable, which has more constraints on it that scala. collection.

How do you turn a list into a sequence?

A java list can be converted to sequence in Scala by utilizing toSeq method of Java in Scala. Here, you need to import Scala's JavaConversions object in order to make this conversions work else an error will occur.

What is the difference between SEQ and list in Scala?

A Seq is an Iterable that has a defined order of elements. Sequences provide a method apply() for indexing, ranging from 0 up to the length of the sequence. Seq has many subclasses including Queue, Range, List, Stack, and LinkedList. A List is a Seq that is implemented as an immutable linked list.


2 Answers

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.

like image 176
Landei Avatar answered Sep 22 '22 17:09

Landei


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

like image 31
Emil Sit Avatar answered Sep 23 '22 17:09

Emil Sit