我正在寻找一种匹配可能包含整数值的字符串的方法。如果是这样,解析它。我想编写类似于以下内容的代码:
def getValue(s: String): Int = s match {
case "inf" => Integer.MAX_VALUE
case Int(x) => x
case _ => throw ...
}
目标是如果字符串等于“inf”,则返回 Integer.MAX_VALUE。如果字符串是可解析的整数,则返回整数值。否则扔。
最佳答案
定义提取器
object Int {
def unapply(s : String) : Option[Int] = try {
Some(s.toInt)
} catch {
case _ : java.lang.NumberFormatException => None
}
}
您的示例方法
def getValue(s: String): Int = s match {
case "inf" => Integer.MAX_VALUE
case Int(x) => x
case _ => error("not a number")
}
并使用它
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...
关于Scala:匹配和解析一个整数字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1075676/