如何将 Java Iterable 转换为 Scala Iterable?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1072784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:30:09  来源:igfitidea点击:

How can I convert a Java Iterable to a Scala Iterable?

scalascala-java-interop

提问by Matt R

Is there an easy way to convert a

有没有简单的方法来转换

java.lang.Iterable[_]

to a

Scala.Iterable[_]

?

?

回答by Alex Cruise

In Scala 2.8 this became much much easier, and there are two ways to achieve it. One that's sort of explicit (although it usesimplicits):

在 Scala 2.8 中,这变得更加容易,并且有两种方法可以实现。一种显式的(尽管它使用隐式):

import scala.collection.JavaConverters._

val myJavaIterable = someExpr()

val myScalaIterable = myJavaIterable.asScala

EDIT:Since I wrote this, the Scala community has arrived at a broad consensus that JavaConvertersis good, and JavaConversionsis bad, because of the potential for spooky-action-at-a-distance. So don't use JavaConversionsat all!

编辑:自从我写这篇文章以来,Scala 社区已经达成了一个广泛的共识,它JavaConverters是好的,JavaConversions也是坏的,因为有可能发生远距离动作。所以根本不用JavaConversions



And one that's more like an implicit implicit: :)

还有一个更像是一种隐含的::)

import scala.collection.JavaConversions._

val myJavaIterable = someExpr()

for (magicValue <- myJavaIterable) yield doStuffWith(magicValue)
import scala.collection.JavaConversions._

val myJavaIterable = someExpr()

for (magicValue <- myJavaIterable) yield doStuffWith(magicValue)

回答by oxbow_lakes

Yes use implicitconversions:

是使用隐式转换:

import java.lang.{Iterable => JavaItb}
import java.util.{Iterator => JavaItr}

implicit def jitb2sitb[T](jit: JavaItb[T]): Iterable[T] = new SJIterable(jit);
implicit def jitr2sitr[A](jit: JavaItr[A]): Iterator[A] = new SJIterator(jit)

Which can then be easily implemented:

然后可以轻松实现:

class SJIterable[T](private val jitb: JavaItr[T]) extends Iterable[T] {
  def elements(): Iterator[T] = jitb.iterator()
}

class SJIterator[T](private val jit: JavaItr[T]) extends Iterator[T] {
  def hasNext: Boolean = jit hasNext

  def next: T = jit next
}

回答by Xavier Guihot

Starting Scala 2.13, package scala.jdk.CollectionConvertersreplaces deprecated packages scala.collection.JavaConverters/JavaConversions:

开始Scala 2.13,包scala.jdk.CollectionConverters替换不推荐使用的包scala.collection.JavaConverters/JavaConversions

import scala.jdk.CollectionConverters._

// val javaIterable: java.lang.Iterable[Int] = Iterable(1, 2, 3).asJava
javaIterable.asScala
// Iterable[Int] = List(1, 2, 3)