Does anyone out there who's familiar with Scala know how I could use scala.collection.immutable.Set from Java? I can vaguely read the scaladoc, but am not sure how to call scala methods like "-" from java (I assume that I just need to include some scala .jar file in my classpath...?)
+6
A:
Scala writes those special symbols out as $plus, $minus, etc. You can see that for yourself by running javap against scala.collection.immutable.HashSet.
That allows you to do code like this:
Set s = new HashSet<String>();
s.$plus("one");
Not pretty, and it doesn't actually work at runtime! You get a NoSuchMethodError. I'm guessing it's related to this discussion. Using the workaround they discuss, you can get things working:
import scala.collection.generic.Addable;
import scala.collection.generic.Subtractable;
import scala.collection.immutable.HashSet;
import scala.collection.immutable.Set;
public class Test {
public static void main(String[] args) {
Set s = new HashSet<String>();
s = (Set<String>) ((Addable) s).$plus("GAH!");
s = (Set<String>) ((Addable) s).$plus("YIKES!");
s = (Set<String>) ((Subtractable) s).$minus("GAH!");
System.out.println(s); // prints Set(YIKES!)
}
}
Isn't that a beauty!?
I believe Java 7 is going to allow funky method names to be escaped, so maybe by then you'll be able to do
s = s.#"-"('GAH!')
To try this, you need scala-library.jar from the lib/ folder of the Scala distribution.
Update: fixed Java 7 syntax, thanks Mirko.
Adam Rabung
2010-06-11 19:43:39
Unfortunately, Java 7's syntax for calling exotic names (http://bugs.sun.com/view_bug.do?bug_id=6746458) isn't that beautiful: s = s.#"-"('GAH!')
Mirko Stocker
2010-06-12 11:48:46
I'm not using Scala 2.8.0 (which has all that Addable/Subtractable stuff) and didn't need to use the casting... the key for me was the naming (e.g. "$plus" and "$minus") and the scala-library.jar -- thanks!
Jason S
2010-06-16 20:34:21
A:
Based on Adam's answer, the following works fine for me with Scala 2.7.7 under Eclipse:
package com.example.test.scala;
import scala.collection.immutable.HashSet;
import scala.collection.immutable.Set;
public class ImmutableSetTest1 {
public static void main(String[] args) {
Set s0 = new HashSet<String>();
Set[] s = new Set[3];
s[0] = s0.$plus("GAH!");
s[1] = s[0].$plus("YIKES!");
s[2] = s[1].$minus("GAH!");
for (int i = 0; i < 3; ++i)
System.out.println("s["+i+"]="+s[i]);
}
}
which prints:
s[0]=Set(GAH!)
s[1]=Set(GAH!, YIKES!)
s[2]=Set(YIKES!)
Jason S
2010-06-16 20:32:50