5

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?

1
  • 3
    I guess it's not problem of method names per se: the cause is likely scala collection hierarchy and contravariance: javac fails to deem scala.collection.Set<String> as scala.collection.immutable.Set<String> Commented Jul 31, 2014 at 10:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.