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)
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)
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)
Using flatMap over util.Try like this,
x.flatMap( s => Try(s.toInt) toOption )
res: List[Int] = List(12, 33, 77)