从Java调用Scala方法-Set< Object>或Set< Long&gt ;? [英] Calling Scala Method from Java - Set<Object> or Set<Long>?

查看:58
本文介绍了从Java调用Scala方法-Set< Object>或Set< Long&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java

Set<Long> set = new HashSet<Long>();
set.add(100);
long x = 2;
foo(x, set);

斯卡拉

def foo(a:Long,b:java.util.Set [Long])

错误:

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

然后,我修改了Java代码以解决编译时错误.

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?

编辑

@ som-snytt 解决了我的问题后

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])

推荐答案

类型错误.Java代码中 set 的类型是 java.util.Set [java.lang.Long] ,而Scala中的类型是 java.util.Set[scala.Long] .在Java中,未将 scala.Long 类型视为原始的 long ,而在擦除时将其视为 java.lang.Object (如您被发现).

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).

因此可以将Scala的类型更改为Java的类型以进行匹配.不幸的是, scala.Long 会擦除为 java.lang.Object ,但这是必需的.

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.

这篇关于从Java调用Scala方法-Set&lt; Object&gt;或Set&lt; Long&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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