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 {
Some(userId.toInt)
} catch {
case e:Exception => None
}
}
val user = toInt("abc")
What changes do I need to make?
source to share
You need map
Option
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 {
Some(userId.toInt)
} 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)
Try(a.toInt)
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.
source to share