Is there a simple way to extract the values of a list into a tuple in Scala?
Basically something like
"15,8".split(",").map(_.toInt).mkTuple //(15, 8)
Or some other way I can do
val (x, y) = "15,8".split(",").map(_.toInt)
If you have them in an array you can write Array in front of the variable names like so:
val Array(x, y) = "15,8".split(",").map(_.toInt)
Just replace with Seq or similar if you have another collection-type.
It basically works just like an extractor behind the scenes. Also see this related thread: scala zip list to tuple
tuple result directly without creating two vals x and y? (I really like inline solutions)You could try pattern matching:
val (x, y) = "15,8".split(",") match {
case Array(x: String, y: String) => (x.toInt, y.toInt)
case _ => (0, 0) // default
}
case _ => (0, 0) part is really suggesting something the original asker did not ask about at all.