Convert a java collections into a scala one from java

19 views
Skip to first unread message

Edmondo Porcu

unread,
Apr 23, 2012, 4:09:04 AM4/23/12
to scala-user
Dear all,
I am trying to call a Scala API from java, so I need to pass a scala collection.

It is clear to me how to do the conversion inside the Scala code, but
how do you them in java? In particularly I am trying to turn a
java.List into a scala List.

Best Regards
Edmondo

Daniel Sobral

unread,
Apr 23, 2012, 9:08:30 AM4/23/12
to Edmondo Porcu, scala-user

Well, from Scala you'd do something like this:

scala.collection.immutable.List$.MODULE$.apply(scala.collection.JavaConversions$.MODULE$.collectionAsScalaIterable(myJavaList).toSeq:
_*)

You might need to sprinkle some type annotations in there, and loose
": _*", when converting it to Java. I'd try to come up with Java's
code, but I have no Java REPL to try it out. :-)

--
Daniel C. Sobral

I travel to the future all the time.

Joshua Serrin

unread,
Apr 23, 2012, 9:54:15 AM4/23/12
to Daniel Sobral, Edmondo Porcu, scala-user
I recommend writing a small class in Scala that takes in an Array[T]
where T is your type. Then have do the conversion from scala's Array
to scala's List invoke the Scala API and then return back an Array.
Scala does the conversion for you automatically when dealing with
Arrays to/from Java so i think that's actually the preferred way for
integration... I think. I'm sure there's a book out there that
explains that in depth (http://www.manning.com/suereth/).

That's MODULE$ stuff just seems hairy.

Shairon Toledo

unread,
Apr 23, 2012, 9:57:19 AM4/23/12
to Joshua Serrin, Daniel Sobral, Edmondo Porcu, scala-user
I've used to use this way

import java.util.{List, ArrayList}
import scala.collection.JavaConverters._

val jlist = new ArrayList[String]
jlist.add("foo")
jlist.add("bar")

val slist = jlist.asScala.toList


although I don't know if it's the more effective way to do it but it's easier.
--











Shairon Toledo
http://hashcode.me

Daniel Sobral

unread,
Apr 23, 2012, 10:57:57 AM4/23/12
to shairon...@gmail.com, Joshua Serrin, Edmondo Porcu, scala-user
Yeah, but that's in Scala, with implicits. From Java, things are more difficult.

Daniel Sobral

unread,
Apr 23, 2012, 11:08:15 AM4/23/12
to Joshua Serrin, Edmondo Porcu, scala-user
The MODULE$ stuff is just the way to use methods from objects. If you
are interacting with Scala from Java, you'd better get used to it.
Reply all
Reply to author
Forward
0 new messages