How to get Scala List from Java List?

I have a Java API that returns a List like:

public List<?> getByXPath(String xpathExpr)

I am using the below scala code:

val lst = node.getByXPath(xpath)

Now if I try scala syntax sugar like:

lst.foreach{ node => ... }

it does not work. I get the error:

value foreach is not a member of java.util.List[?0]

It seems I need to convert Java List to Scala List. How to do that in above context?


Solution 1:

EDIT: Note that this is deprecated since 2.12.0. Use JavaConverters instead. (comment by @Yaroslav)

Since Scala 2.8 this conversion is now built into the language using:

import scala.collection.JavaConversions._

...

lst.toList.foreach{ node =>   .... }

works. asScala did not work

In 2.12.x use import scala.collection.JavaConverters._

In 2.13.x use import scala.jdk.CollectionConverters._

Solution 2:

There's a handy Scala object just for this - scala.collection.JavaConverters

You can do the import and asScala afterwards as follows:

import scala.collection.JavaConverters._

val lst = node.getByXPath(xpath).asScala
lst.foreach{ node =>   .... }

This should give you Scala's Buffer representation allowing you to accomplish foreach.