I am reading and parsing a json file. One of the field of the json file is Nullable. It either returns a string of digits or Null. I need to convert the string to int. I am able to convert from String to Option[Int] by the below code, but not able to 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 do?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With