1

In scala, how can I initialize a scala collection from a Java iterable, in a clean idiomatic way?

Here's somewhat lame code taking a less functional approach for that:

var collection = Seq[MyClass]() 

while (iterator.hasNext) { 
  val asArray: Array[String] = iterator.next.toArray
  val val2 = asArray(2)
  val val3 = asArray(3)
  collection = collection :+ new MyClass(val2, val3)
}

How can initialization of a collection from a Java iterable take place more idiomatically?

2 Answers 2

1
import scala.collection.JavaConverters._

val collection = iterator.asScala.map{ x =>
  val asArray = x.toArray
  new MyClass(asArray(2), asArray(3))
}.toIndexedSeq
Sign up to request clarification or add additional context in comments.

Comments

0

Scala can convert to and from Java collections seamlessly, provided you have imported the conversion helpers like below:

import scala.collection.JavaConversions._
val jl = new java.util.ArrayList[String]()
jl.add("Hello")
jl.add("There")

val collection = j1.map{ x => new MyClass(x(2), x(3)) }.toList

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.