How do I convert Option [String] to Option [Int]?

I am reading and parsing a json file. One of the fields in the json file is Nullable. It either returns a string of digits or Null. I need to convert a string to int. I can convert from String to Option [Int] with the below code, but could not convert from Option [String] to Option [Int]

 def toInt(userId: String):Option[Int] = {
  try {
  } catch {
    case e:Exception => None

val user = toInt("abc")


What changes do I need to make?


source to share

3 answers

import util.Try

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



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

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

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






Use Option

instead Some

. Then use map

to convert it toInt



You need map


to do something with the possible contained value. In the context of your code, I would use flatMap

since the current method returns Option

, so we have to flatten out what would be nested Option


def toInt(userIdOpt: Option[String]): Option[Int] = userIdOpt flatMap { userId =>
  try {
  } catch {
    case e:Exception => None

scala> val u = Option("2")
u: Option[String] = Some(2)

scala> toInt(u)
res0: Option[Int] = Some(2)

scala> toInt(Some("a"))
res4: Option[Int] = None


We can shorten this by using Try


import scala.util.Try

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



returns a Try[Int]

where a successful conversion will be Success[Int]

and a failed conversion (not an integer) will be Failure[Throwable]

. Try

has a very handy method called toOption

, which converts Success(a)

to Some(a)

and Failure

to None

what we want.



All Articles