从java中使用scala.collection.immutable.Set的示例 [英] example of using scala.collection.immutable.Set from java

查看:350
本文介绍了从java中使用scala.collection.immutable.Set的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁熟悉Scala的人知道如何使用 scala.collection.immutable.Set 从Java?我可以模糊地读取scaladoc,但不知道如何从java调用像 - 这样的Scala方法(我假设我只需要在我的classpath中包含一些scala .jar文件...)

解决方案

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆