Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a while() loop for an Iterable<Object> in Scala?

Tags:

scala

I'm learning Scala and I want to transform a line of code from Java. I've tried 2 methods in scala, but they didn't work. The class ResultScanner comes from Apache HBase - ResultScanner and the same for the Result class

Java

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

I've tried the following as well :

resultScanner.foreach(println(_)) // error[2]

// error[2]: value foreach is not a member of org.apache.hadoop.hbase.client.ResultScanner
like image 364
Mincong Huang Avatar asked Dec 19 '22 00:12

Mincong Huang


2 Answers

Include import scala.collection.JavaConverters._ for Java to Scala collections portability. Then invoke asScala on the collection,

resultScanner.asScala foreach println
like image 157
elm Avatar answered Jan 09 '23 21:01

elm


Instead of ArrayList create ResultScanner and try:

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

Note:

Choose JavaConverters._ instead of 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)
like image 26
Andrzej Jozwik Avatar answered Jan 09 '23 21:01

Andrzej Jozwik