从java中使用scala.collection.immutable.Set的示例 [英] example of using scala.collection.immutable.Set from java
问题描述
Scala将这些特殊符号写成$ plus,$ minus等。您可以通过运行javap来反映scala.collection.immutable。哈希集
这样可以执行如下代码:
设置= new HashSet< String>();
s。$ plus(one);
不漂亮,它在运行时实际上不起作用!你得到一个NoSuchMethodError。我猜这是与这个讨论。使用他们讨论的解决方法,您可以使工作:
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))$ plus(GAH!);
s =(Set< String>)((Addable)s)。$ plus(YIKES!);
s =(Set< String>)((Subtractable))$ minus(GAH!);
System.out.println(s); //打印Set(YIKES!)
}
}
不是那个美丽!
我相信Java 7将允许时髦的方法名称被转义,所以也许你可以做到这一点。
s = s。# - ('GAH!')
要尝试这样做,您需要Scala发行版的lib /文件夹中的scala-library.jar。
更新:修复Java 7语法,谢谢Mirko。
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...?)
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.
这篇关于从java中使用scala.collection.immutable.Set的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!