It looks like there's some magic translation between Java data structures when accessing them from JRuby; they appear to work like plain ruby maps and arrays. However, Scala data structures don't. I found surprisingly little when googling around for JRuby / Scala interop. How would you, for instance, iterate over Scala's Map
and List
types?
Sure you can. But it's a bit of hoop-jumping. For lists:
require "/usr/share/scala/lib/scala-library.jar" # load the scala lib
Java::scala.collection.immutable::List.empty.send("::", 1)
.map(lambda{|e|e+1},
Java::scala.collection.immutable.List.canBuildFrom) # by lopex
Now you have a scala list in jruby. You could write some nice Ruby API filling in the implicits for you.
If by "iterate over" you mean use the HOFs (higher-order functions) such as map
, reduce
, filter
, collect
and so on then you're going to have trouble. It's possible, but the syntactic elegance you get in Scala comes because it's so easy to write function literals. What the compiler is doing for you when you write something like this:
scala> val l1 = List(1, 2, 3)
l1: List[Int] = List(1, 2, 3)
scala> l1.map(i => i * i)
res0: List[Int] = List(1, 4, 9)
... is create and instantiate a subclass of Function1[Int, Int]
whose apply
method takes the single Int
argument an evaluates the body of the function literal ((i => i * i)
).
For you to use any Scala method that accepts a function you'll have to do the same. Something like:
scala> class ISquaredF extends Function1[Int, Int] { def apply(i: Int) = i * i }
defined class ISquaredF
scala> (new ISquaredF)(5)
res1: Int = 25
scala> val isf1 = new ISquaredF
isf1: ISquaredF = <function1>
scala> l1.map(isf1)
res2: List[Int] = List(1, 4, 9)
Overall, it's vastly easier to use Java libraries from Scala than it is to use Scala code from any other JVM language. That's why systems like Akka that want to support both Scala and Java clients have special Java APIs that avoid these parts of the Scala language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With