Scala: match and parse an integer string?
This is better IMHO:
val IntRegEx = "(\\d+)".r
def getValue(s: String): Option[Int] =
s match {
case "inf" => Some(Int.MaxValue)
case IntRegEx(num) => Some(num.toInt)
case _ => None
}
getValue("inf") // Some(2147483647)
getValue("123412") // Some(123412)
getValue("not-a-number") // None
Of course, it doesn't throw any exceptions, but if you really want it, you may use:
getValue(someStr).getOrElse(error("NaN"))
Define an extractor
object Int {
def unapply(s : String) : Option[Int] = try {
Some(s.toInt)
} catch {
case _ : java.lang.NumberFormatException => None
}
}
Your example method
def getValue(s: String): Int = s match {
case "inf" => Integer.MAX_VALUE
case Int(x) => x
case _ => error("not a number")
}
And using it
scala> getValue("4")
res5: Int = 4
scala> getValue("inf")
res6: Int = 2147483647
scala> getValue("helloworld")
java.lang.RuntimeException: not a number
at scala.Predef$.error(Predef.scala:76)
at .getValue(<console>:8)
at .<init>(<console>:7)
at .<clinit>(<console>)
at RequestResult$.<init>(<console>:4)
at RequestResult$.<clinit>(<console>)
at RequestResult$result(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Na...