Scala: convert string to Int or None

doub1ejack picture doub1ejack · May 22, 2014 · Viewed 36.4k times · Source

I am trying to get a number out of an xml field

...
<Quantity>12</Quantity>
...

via

Some((recipe \ "Main" \ "Quantity").text.toInt)

Sometimes there may not be a value in the xml, though. The text will be "" and this throws an java.lang.NumberFormatException.

What is a clean way to get either an Int or a None?

Answer

R&#233;gis Jean-Gilles picture Régis Jean-Gilles · May 22, 2014
scala> import scala.util.Try
import scala.util.Try

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

scala> tryToInt("123")
res0: Option[Int] = Some(123)

scala> tryToInt("")
res1: Option[Int] = None