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
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
}
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