UberMouse
UberMouse

Reputation: 937

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)

Upvotes: 18

Views: 10546

Answers (2)

Jens Egholm
Jens Egholm

Reputation: 2710

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

Upvotes: 41

rocky3000
rocky3000

Reputation: 1120

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
}

Upvotes: 5

Related Questions