How to convert a Option[String] to Option[Int]?

import util.Try

def toInt(o: Option[String]): Option[Int] =
  o.flatMap(s => Try(s.toInt).toOption)

Examples:

scala> toInt(None)
res0: Option[Int] = None

scala> toInt(Some("42"))
res1: Option[Int] = Some(42)

scala> toInt(Some("abc"))
res2: Option[Int] = None

Option(userId).map(_.toInt)

Use Option instead of Some. Than use map to convert it to Int


Scala 2.13 introduced String::toIntOption:

Which combined to a flatMap provides a safe way to cast from Option[String] to Option[Int]:

Option("1").flatMap(_.toIntOption)            // Option[Int] = Some(1)
(None: Option[String]).flatMap(_.toIntOption) // Option[Int] = None
Option("abc").flatMap(_.toIntOption)          // Option[Int] = None
Option(null: String).flatMap(_.toIntOption)   // Option[Int] = None

Tags:

Json

Scala