将 Scala Set 转换为 Java (java.util.Set)?
我在 Scala 中有一个 Set(在创建 Set 时可以选择任何实现。我使用的 Java 库需要 java.util.Set[String]。
以下是在 Scala 中执行此操作的正确方法吗(使用scala.collection.jcl.HashSet#underlying):
import com.javalibrary.Animals
var classes = new scala.collection.jcl.HashSet[String]
classes += "Amphibian"
classes += "Reptile"
Animals.find(classes.underlying)
它似乎有效,但由于我对 Scala 很陌生,我想知道这是否是首选方式(我尝试的任何其他方式都会收到类型不匹配错误) :
error: type mismatch;
found : scala.collection.jcl.HashSet[String]
required: java.util.Set[_]
I have a Set in Scala (I can choose any implementation as I am creating the Set. The Java library I am using is expecting a java.util.Set[String].
Is the following the correct way to do this in Scala (using scala.collection.jcl.HashSet#underlying):
import com.javalibrary.Animals
var classes = new scala.collection.jcl.HashSet[String]
classes += "Amphibian"
classes += "Reptile"
Animals.find(classes.underlying)
It seems to be working, but since I am very new to Scala I want to know if this is the preferred way (any other way I try I am getting a type-mismatch error):
error: type mismatch;
found : scala.collection.jcl.HashSet[String]
required: java.util.Set[_]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您询问 Scala 2.8,Java 集合互操作性由 scala.collection.JavaConversions 提供。在本例中,您需要 JavaConversions.asSet(...) (每个方向都有一个,Java -> Scala 和 Scala -> Java)。
对于 Scala 2.7,包装 Java 集合的每个 scala.collection.jcl 类都有一个提供包装的 Java 集合实例的
underlying
属性。If you were asking about Scala 2.8, Java collections interoperability is supplied by
scala.collection.JavaConversions
. In this case, you want JavaConversions.asSet(...) (there's one for each direction, Java -> Scala and Scala -> Java).For Scala 2.7, each scala.collection.jcl class that wraps a Java collection has an
underlying
property which provides the wrapped Java collection instance.自 Scala 2.12.0 起
scala.collection.JavaConversions
已弃用:从 Scala 2.8.1 开始,您可以 为此目的使用
scala.collection.JavaConverters
:Since Scala 2.12.0
scala.collection.JavaConversions
is deprecated:And since Scala 2.8.1 you can use
scala.collection.JavaConverters
for this purpose:请注意,从 Scala 2.13 开始,包
scala.jdk.CollectionConverters
替换已弃用的包scala.collection.JavaConverters/JavaConversions._
:Note that starting
Scala 2.13
, packagescala.jdk.CollectionConverters
replaces deprecated packagesscala.collection.JavaConverters/JavaConversions._
:对于 2.7.x,我强烈建议使用: http://github.com/ jorgeortiz85/scala-javautils
For 2.7.x I highly recommend using: http://github.com/jorgeortiz85/scala-javautils
在 Scala 2.12 中可以使用: scala.collection.JavaConverters.setAsJavaSet(scalaSetInstance)
In Scala 2.12 it is possible to use :
scala.collection.JavaConverters.setAsJavaSet(scalaSetInstance)