我正在学习Scala,我想从Java转换一行代码。我在scala中尝试了两种方法,但它们没有用。类ResultScanner
来自Apache HBase - ResultScanner,同样适用于Result类
爪哇
for(Result r : resultScanner) System.out.println(r)
Scala
while(resultScanner.hasNext) // error[1]
println(resultScanner.next())
//error[1]: value hasNext is not a member of org.apache.hadoop.hbase.client.ResultScanner
我也尝试了以下内容:
resultScanner.foreach(println(_)) // error[2]
// error[2]: value foreach is not a member of org.apache.hadoop.hbase.client.ResultScanner
答案 0 :(得分:9)
将Java import scala.collection.JavaConverters._
包含在Scala集合可移植性中。然后在集合上调用asScala
resultScanner.asScala foreach println
答案 1 :(得分:2)
而不是ArrayList创建ResultScanner并尝试:
scala> import java.util
import java.util
scala> import scala.collection.JavaConversions._
import scala.collection.JavaConversions._
scala> val jList = new util.ArrayList[Int]
jList: java.util.ArrayList[Int] = []
scala> jList.add(2)
res4: Boolean = true
scala> jList.add(6)
res5: Boolean = true
scala> val iterable = iterableAsScalaIterable(jList)
iterable: Iterable[Int] = Wrappers(2, 6)
scala> iterable.foreach(println)
2
6
注意:强>
选择JavaConverters._
而不是JavaConverters._
scala> import scala.collection.JavaConverters._
import scala.collection.JavaConverters._
scala> import java.util
import java.util
scala> val jList = new util.ArrayList[Int]
jList: java.util.ArrayList[Int] = []
scala> jList.add(2)
res0: Boolean = true
scala> jList.add(6)
res1: Boolean = true
scala> val iterable = jList.asScala
iterable: scala.collection.mutable.Buffer[Int] = Buffer(2, 6)
scala> val iterable:Iterable[Int] = jList.asScala
iterable: Iterable[Int] = Buffer(2, 6)