Scala List to mutable JDK List

What is the idiomatic way to convert a scala List to a mutable JDK list type like LinkedList?

I tried

List(1, 2, 3).to[BufferdList].asJava

but apparently I am missing a factory which is used int to, so this did not do the trick.

What about this:

def toLinkedList[T](list: List[T]): LinkedList[T] =
  new LinkedList(list.asJava)

You can see it running here.


Well, this works always, I thought there was a built-in way to get a ListBuffer from a List.

Not there isn’t one, for a very simple reason.
The asJava methods do not copy data but rather provide a wrapper, however since LinkedList is not an interface but rather a concrete collection, you need to copy the data and the jdk.CollectionConverters wants that you are explicit about that copying.

Now, if you didn’t need a specific LinkedList but rather just a List (which you should) then you can just:

def toJavaList[T](list: List[T]): java.util.List[T] =[Buffer].asJava

You can see it running here.

I already tried something like this:

implicit def listToObservableList[A](list: List[A]): ObservableList[A] = FXCollections.observableList([mutable.Buffer].asJava

But here I get an error: trait Buffer takes type parameters[mutable.Buffer].asJava.

Are you in Scala 2.13? If so you should be doing (note the parenthesis instead of braces).

1 Like

Well, with the parenthesis it worked. Why did this change? in 2.13?