Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

example of using scala.collection.immutable.Set from java

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...?)

like image 416
Jason S Avatar asked Feb 03 '23 04:02

Jason S


1 Answers

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.

like image 116
Adam Rabung Avatar answered Feb 05 '23 19:02

Adam Rabung