kenp
kenp

Reputation: 500

How to convert an Option[String]to List [Int]in Scala

I'm able to convert Option[String] to List[String] with the following code :

 def convertOptionToListString(a: Option[String]): List[String] = {
    return a.toList.flatMap(_.split(",")) // ex : ("value1", "value2", "value3", etc)
  }

But how can i convert Option[String] to List[Int] so at the end i can have list with integers : (1,3,5). My Option[String] will looks like this : Some("1,3,5")

Note that the values 1,3,5 comes from params.get("ids") sent from an url and params.get is an Option[String]

val params = request.queryString.map { case (k, v) => k -> v(0) }

Thanks

Upvotes: 1

Views: 1951

Answers (4)

Xavier Guihot
Xavier Guihot

Reputation: 61666

Scala 2.13 introduced String::toIntOption.

Combined with a flatMap, we can safely cast Strings into Ints and eliminate malformed inputs:

List("1", "2", "abc").flatMap(_.toIntOption)
// List[Int] = List(1, 2)

Upvotes: 2

MattPutnam
MattPutnam

Reputation: 3017

From where you are, you just need to map toInt over it. But your order of operations is kind of weird. It's like you're using toList just to satisfy the type. toList is one of those smelly functions where if you're using it you're probably abusing something.

The logic that reads the best is that if you have a Some, then process it, otherwise you just default to the empty list (I'm guessing):

option match {
  case Some(str) => str.split(",").map(_.toInt)
  case None => List()
}

Or:

option.map(_.split(",").map(_.toInt)).getOrElse(List())

Upvotes: 0

dhg
dhg

Reputation: 52681

val a: Option[String] = Some("1,3,5")
val l = a.toList.flatMap(_.split(",")).map(_.toInt)

Upvotes: 0

Aivean
Aivean

Reputation: 10882

If you want to convert List[String] to List[Int], skipping unparseable values, then you can use Try:

import scala.util.Try

List("1", "2", "3").flatMap(x => Try(x.toInt).toOption)
res0: List[Int] = List(1, 2, 3)

List("1", "2", "abc").flatMap(x => Try(x.toInt).toOption)
res1: List[Int] = List(1, 2)

Upvotes: 1

Related Questions