Reputation: 41919
Java
Set<Long> set = new HashSet<Long>();
set.add(100);
long x = 2;
foo(x, set);
Scala
def foo(a: Long, b: java.util.Set[Long])
Error:
could not parse error message:
required: long,Set<Object>
found: long,Set<Long>
reason: actual argument Set<Long> cannot be converted
to Set<Object> by method invocation conversion
Then, I modified my Java code to resolve the compile-time error.
Set<Object> set = new HashSet<Object>();
However, the resolution of the compile-time error came at the expense of type safety. How can I properly resolve the above error?
EDIT
After @som-snytt resolved my issues here, I ran into this problem. I don't think it's the same question since , in my linked question, using, in Scala, foo(Long, java.util.Set[Long])
worked when calling (from Java) ScalaObject.foo(long, Set[Long])
Upvotes: 2
Views: 685
Reputation: 297265
The types are wrong. The type of set
in the Java code is java.util.Set[java.lang.Long]
, while the type in Scala is java.util.Set[scala.Long]
. The scala.Long
type is treated as the primitive long
in Java, when not erased, and as java.lang.Object
when erased (as you uncovered).
So either change Scala's type to Java's type to match. It's unfortunate that scala.Long
erases to java.lang.Object
, but necessary.
Upvotes: 5
Reputation: 1775
You probably want to import JavaConverters
in this case.
import scala.collection.JavaConverters._
def foo(a: Long, b: java.util.Set[Long]) = ???
Upvotes: 0