18

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)

2 Answers 2

41

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

Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to create tuple result directly without creating two vals x and y? (I really like inline solutions)
5

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
}

3 Comments

I was really hoping for something a bit less verbose, it's simpler to do it the way I'm currently doing it which is var s = l.split(",").map(_.toInt) val (x, n) = (s(0), s(1)) I was just hoping to get rid of the intermediate step with 's'
With pattern matching you can easiely return a fallback value if you don't get two strings from split and it's not introducing unnecessary vals.
Just for the record: the case _ => (0, 0) part is really suggesting something the original asker did not ask about at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.