views:

3963

answers:

2

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.

+1  A: 
def getValue(s: String): Int = s match {
    case "inf" => Integer.MAX_VALUE 
    case _ => s.toInt
}


println(getValue("3"))
println(getValue("inf"))
try {
    println(getValue("x"))
}
catch {
    case e => println("got exception", e)
    // throws a java.lang.NumberFormatException which seems appropriate
}
agilefall
This is actually a good way to meet my immediate needs, however it's not the generic solution i was looking for. For instance, perhaps I would want to execute a block depending on what type the string was parsable to: def doSomething(s: String): Int = s match { case Int(x) => println("you got an int") case Float(x) => println("you got a float") case _ => throw ... }
landon9720
+12  A: 

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...
James Iry
So you can just open up an object { } like that and add methods to an existing class? Cool (I think...).
landon9720
Never mind, I understand now that object Int{} is creating a new Int class in your namespace.
landon9720
It actually might be more efficient to use regular expressions to match the contents of the string, rather than catching the exception.
Daniel Spiewak