如何将Java Iterable转换为Scala Iterable? [英] How can I convert a Java Iterable to a Scala Iterable?

查看:326
本文介绍了如何将Java Iterable转换为Scala Iterable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法来转换

Is there an easy way to convert a

java.lang.Iterable[_]

Scala.Iterable[_]

?

推荐答案

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

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 uses implicits):

import scala.collection.JavaConverters._

val myJavaIterable = someExpr()

val myScalaIterable = myJavaIterable.asScala

自从我写这篇文章以来,Scala社区已经达成了广泛共识,即JavaConverters是好事,而JavaConversions是坏事,因为它可能会引起诡异的动作. -一个距离.所以根本不要使用JavaConversions

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

一个更像是一个隐式隐式::)

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

import scala.collection.JavaConversions._

val myJavaIterable = someExpr()

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

这篇关于如何将Java Iterable转换为Scala Iterable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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