1

So, I have a list of strings like this.

val x = List("12", "33", "77")

Is there a way to convert this whole List into integer values, like the following, without using a for loop?

result == List(12, 33, 77)
1
  • Vow, this syntax is awesome. Scala seems a pretty cool language. Commented Nov 15, 2014 at 16:54

2 Answers 2

4

map the List using toInt :

List("12", "33", "77").map(_.toInt)

Or with a little more safety:

import scala.util.{Success, Try}
List("12", "33", "77", "bad").map(s => Try(s.toInt))
    .collect { case Success(x) => x }

res2: List[Int] = List(12, 33, 77)

Also:

List("12", "33", "77", "bad").filter(_.matches("[0-9]+")).map(_.toInt)
res7: List[Int] = List(12, 33, 77)
Sign up to request clarification or add additional context in comments.

Comments

2

Using flatMap over util.Try like this,

x.flatMap( s => Try(s.toInt) toOption )
res: List[Int] = List(12, 33, 77)

1 Comment

That wiil silently discard bad entries

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.