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
Include import scala.collection.JavaConverters._
for Java to Scala collections portability. Then invoke asScala
on the collection,
resultScanner.asScala foreach println
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With