Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

scala

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?

like image 290
Goku__ Avatar asked Apr 30 '15 11:04

Goku__


1 Answers

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
like image 76
Chris Martin Avatar answered Oct 14 '22 20:10

Chris Martin