Convert Java List to Scala Seq

Fundhor picture Fundhor · Mar 14, 2016 · Viewed 55.5k times · Source

I need to implement a method that returns a Scala Seq, in Java.

But I encounter this error:

java.util.ArrayList cannot be cast to scala.collection.Seq

Here is my code so far:

@Override
public Seq<String> columnNames() {
    List<String> a = new ArrayList<String>();
    a.add("john");
    a.add("mary");
    Seq<String> b = (scala.collection.Seq<String>) a;
    return b;
}

But scala.collection.JavaConverters doesn't seem to offer the possibility to convert as a Seq.

Answer

Fundhor picture Fundhor · Mar 14, 2016

JavaConverters is what I needed to solve this.

import scala.collection.JavaConverters;

public Seq<String> convertListToSeq(List<String> inputList) {
    return JavaConverters.asScalaIteratorConverter(inputList.iterator()).asScala().toSeq();
}