Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

i.e. 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

eclipse screenshot

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?

like image 960
muttonUp Avatar asked Nov 11 '22 04:11

muttonUp


1 Answers

It would appear that you can't code to some scala interfaces in Java!
This code compiles and executes correctly in Sun and Eclipse.

Note the use of HashSet on the left hand side of the assignment

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.

For instance, HashSet extends AbstractSet, Set, GenericSetTemplate,SetLike, FlatHashTable, CustomParallelizable, Serializable some of which are interfaces some of which are 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.

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.

I think the main problem here is Elipse somehow misrepresenting the Supertype as having as those methods, which is wrong.

like image 119
muttonUp Avatar answered Nov 14 '22 21:11

muttonUp