Scala: match and parse an integer string?

Landon Kuhn picture Landon Kuhn · Jul 2, 2009 · Viewed 34.9k times · Source

I'm looking for a way to matching a string that may contain an integer value. If so, parse it. I'd like to write code similar to the following:

  def getValue(s: String): Int = s match {
       case "inf" => Integer.MAX_VALUE 
       case Int(x) => x
       case _ => throw ...
  }

The goal is that if the string equals "inf", return Integer.MAX_VALUE. If the string is a parsable integer, return the integer value. Otherwise throw.

Answer

James Iry picture James Iry · Jul 2, 2009

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...