Suppose that I have a string in scala and I want to try to parse a double out of it.
I know that, I can just call toDouble
and then catch the java num
scala> import scala.util.Try
import scala.util.Try
scala> def parseDouble(s: String): Option[Double] = Try { s.toDouble }.toOption
parseDouble: (s: String)Option[Double]
scala> parseDouble("3.14")
res0: Option[Double] = Some(3.14)
scala> parseDouble("hello")
res1: Option[Double] = None
Unfortunately, this isn't in the standard library. Here's what I use:
class SafeParsePrimitive(s: String) {
private def nfe[T](t: => T) = {
try { Some(t) }
catch { case nfe: NumberFormatException => None }
}
def booleanOption = s.toLowerCase match {
case "yes" | "true" => Some(true)
case "no" | "false" => Some(false)
case _ => None
}
def byteOption = nfe(s.toByte)
def doubleOption = nfe(s.toDouble)
def floatOption = nfe(s.toFloat)
def hexOption = nfe(java.lang.Integer.valueOf(s,16))
def hexLongOption = nfe(java.lang.Long.valueOf(s,16))
def intOption = nfe(s.toInt)
def longOption = nfe(s.toLong)
def shortOption = nfe(s.toShort)
}
implicit def string_parses_safely(s: String) = new SafeParsePrimitive(s)