Search code examples
scalascala-option

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


Solution

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