简体   繁体   English

scala运算符作为java中的方法

[英]scala operators as methods in java

When manipulating scala objects (primarily from the the scala.collection package) the operator overloaded functions seem to be available to be used in Java. 在操作scala对象(主要来自scala.collection包)时,操作符重载函数似乎可用于Java。

ie in scala 即斯卡拉

var s = Set(1, 2, 3)
var t = s + 4
var x = s | t

so in Java, looking at scala.collection.Set in eclipse autocomplete, I can see the prototypes 所以在Java中,在eclipse自动完成中查看scala.collection.Set ,我可以看到原型

eclipse截图

But I'm unable to use them correctly 但是我无法正确使用它们

import scala.collection.Set;

Set<Integer> s = new Set<Integer>();
Set<Integer> t = s.$plus(4); /* compile error with javac, or runtime error with eclipse/*

How are these scala methods meant to be used from within Java? 这些scala方法如何在Java中使用?

It would appear that you can't code to some scala interfaces in Java! 您似乎无法使用Java中的某些scala接口进行编码!
This code compiles and executes correctly in Sun and Eclipse. 此代码在Sun和Eclipse中正确编译和执行。

Note the use of HashSet on the left hand side of the assignment 注意在赋值的左侧使用HashSet

import scala.collection.HashSet;

public class TestCase1 {

    public static void main(String[] args) {
        HashSet<String> set2 = new HashSet<String>();

        HashSet<String> set4 = set2.$plus("test");

        System.out.println(set2.size());
        System.out.println(set4.size());


    }
}

Why is this the case? 为什么会这样?

I believe it has something to do with Scalas ability to inherit multiple traits, which java eclipse doesn't understand. 我相信它与Scalas继承多个特征的能力有关,这是java eclipse无法理解的。

For instance, HashSet extends AbstractSet, Set, GenericSetTemplate,SetLike, FlatHashTable, CustomParallelizable, Serializable some of which are interfaces some of which are AbstractClasses. 例如,HashSet扩展了AbstractSet, Set, GenericSetTemplate,SetLike, FlatHashTable, CustomParallelizable, Serializable ,其中一些接口是AbstractClasses。

The .$plus() Method would appear to come from SetLike , not Set , which would explain why calling the method on the Set Supertype would cause this error. .$plus()方法将显示为来自SetLike ,不Set ,这可以解释为什么呼吁的方法Set父类型会导致此错误。

That said I still can't refer to HashSet using the Supertype SetLike as that still fails, and thats as far as I can go. 那说我仍然不能使用SetLike来引用HashSet ,因为它仍然失败,这就是我可以去的。

I think the main problem here is Elipse somehow misrepresenting the Supertype as having as those methods, which is wrong. 我认为这里的主要问题是Elipse以某种方式歪曲Supertype作为那些方法,这是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM