In java code, getting a scala.Iterable from a java.util.List

I knew this ‘How can I convert a Java Iterable to a Scala Iterable?

But I am working on java 1.4.2 code with a scala API.

How can I get a scala.Iterable from a java.util.List?

Thank you for your suggestion.

Answer

Everything you need is in scala.lang.JavaConversions

import java.util.{List => JList, ArrayList}
import scala.collection.JavaConversions._

val jul1: JList[String] = new ArrayList[String]; jul1.add("Boo!")

val sb1 = jul1.toBuffer
val ss1 = jul1.toSeq // Same result as toBuffer

This produces a mutable collection in sml1 (a Buffer). If you want an immutable collection (List, e.g.) convert that mutable collection:

val sl1 = jul1.toList

Edit: Hmm… Java 1.4.2? That’s pre-generics? (I lose track of such ancient history…) This probably won’t work, then… You’ll probably need to work with existential types.

Leave a Reply

Your email address will not be published. Required fields are marked *