placplacboom placplacboom - 26 days ago 19
Scala Question

Scala - Convert List[String] to tuple List[(Int, Int)]

I would like to getLine from a Source and convert it to a tuple (Int, Int). I've did it using foreach.

val values = collection.mutable.ListBuffer[(Int, Int)]()

Source.fromFile(invitationFile.ref.file).getLines().filter(line => !line.isEmpty).foreach(line => {
val value = line.split("\\s")

values += ((value(0).toInt, (value(1).toInt)))
})


What's the best way to write the same code without use foreach?

Answer

Use map, it builds a new list for you:

Source.fromFile(invitationFile.ref.file)
.getLines()
.filter(line => !line.isEmpty)
.map(line => {
  val value = line.split("\\s")
  ((value(0).toInt, (value(1).toInt)))
})
.toList()
Comments