Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract values from Array into Tuple

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)
like image 460
UberMouse Avatar asked May 27 '13 02:05

UberMouse


2 Answers

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

like image 70
Jens Egholm Avatar answered Sep 21 '22 18:09

Jens Egholm


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
}
like image 29
rocky3000 Avatar answered Sep 19 '22 18:09

rocky3000