Scala:匹配和解析一个整数字符串?

标签 scala parsing match

我正在寻找一种匹配可能包含整数值的字符串的方法。如果是这样,解析它。我想编写类似于以下内容的代码:

  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/

相关文章:

java android 将资源文件路径传递给方法参数

java - 什么会让我的 html 解析代码更有效?

php - MySQL Closest Match 使用 ABS 混淆

python - 避免重新计算的方案

scala - 使用 json4s 将 [String,Any] 映射到压缩 json 字符串

java - 在 Lagom 中访问 URL 查询参数

scala - Apache Kafka - 向后分支 162 上存在未初始化的对象

java - 如何漂亮地打印 GumTreeDiff ITree?

python - python Pandas/numpy 的 R 的 match() 等价物是什么?

linked-list - Ocaml双链表: remove a node satisfying a condition from a double linked list