Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中对Scala代码使用'Set'参数_Java_Scala - Fatal编程技术网

在Java中对Scala代码使用'Set'参数

在Java中对Scala代码使用'Set'参数,java,scala,Java,Scala,我试图从Java代码中调用ScalaUtil对象: Main.java Set<Long> items = new HashSet<Long>(); // fill up items with Long MyUtil.foo(100, items); object Foo { type Id = Long def foo(id: Id, items: scala.collection.mutable.Set[Id]) 以下是编译时错误: could not

我试图从Java代码中调用Scala
Util
对象:

Main.java

Set<Long> items = new HashSet<Long>();
// fill up items with Long
MyUtil.foo(100, items);
object Foo {
 type Id = Long
 def foo(id: Id, items: scala.collection.mutable.Set[Id]) 
以下是编译时错误:

  could not parse error message:   
  required: long,scala.collection.mutable.Set<Object>
  found: Long,java.util.Set<Long>
  reason: actual argument java.util.Set<Long> cannot be converted to 
      scala.collection.mutable.Set<Object> by method invocation conversion`
无法分析错误消息:
必需:long,scala.collection.mutable.Set
找到:Long,java.util.Set
原因:实际参数java.util.Set无法转换为
scala.collection.mutable.Set按方法调用转换`
从阅读这些Java到Scala集合,我使用的是一个
mutable
集,而不是默认的不可变集:

scala.collection.mutable.Set java.util.Set


但是,我不理解错误信息。通过在我的Java代码中使用
Long
(盒装
Long
),为什么会找到
集?

演示评论者所说的:

scala> import collection.JavaConverters._
import collection.JavaConverters._

scala> val js = (1 to 10).toSet.asJava
js: java.util.Set[Int] = [5, 10, 1, 6, 9, 2, 7, 3, 8, 4]

scala> def f(is: collection.mutable.Set[Int]) = is.size
f: (is: scala.collection.mutable.Set[Int])Int

scala> def g(js: java.util.Set[Int]) = f(js.asScala)
g: (js: java.util.Set[Int])Int

scala> g(js)
res0: Int = 10
使用Java代码中的Scala集合和类型别名(而不是相反,如图所示:)至少会令人讨厌,很可能会非常痛苦,而且很可能是不可能的

如果您能够修改API的Scala端,我建议您向其添加一个Java友好的API。如果没有,我想您可以在Scala中构建一个适配器层,通过本机Scala API代理Java客户机

比如说:

// Original Scala
object Foo {
  type Id = Long
  def foo(id: Id, items: scala.collection.mutable.Set[Id]) 
}

// Java adapter -- generics might be made to work on the Java side, 
// but Long is particularly problematic, so we'll just force it here
object FooJ {
  import scala.collection.JavaConverters._

  def foo(id: Long, items: java.util.Set[Long]) = {
    Foo.foo(id, items.asScala)
  }
}

据我所知,这些转换在
.scala
中工作。Java不能像那样从A类转换为B类。为什么要投反对票?这个问题真的那么简单吗?嗨@som snytt。
error:value-toSet不是java.util.Set[Long]的成员
出现在这里:
foo(items:java.util.Set[Long]){val-scalaSet=items.toSet}
原因是
java.util.Set
类型?是。因此,首选习惯用法是使用javaconverter(而不是转换),并调用asJava和asScala进行转换,如图所示。然后在使用Java集的方法中,首先对其调用asScala。您也可以调用js.asScala.toSet来构建一个不可变集。如果你有时间,请看一看。谢谢,谢谢。也许这是显而易见的,但是
ju.Set[Long]
java.util.Set[Long]
的缩写?哇,是的。固定的。:)