Scala:匹配并解析整数字符串?
发布时间:2020-12-16 09:46:38 所属栏目:安全 来源:网络整理
导读:我正在寻找一种匹配可能包含整数值的字符串的方法。如果是这样,解析它。我想编写类似于以下内容的代码: def getValue(s: String): Int = s match { case "inf" = Integer.MAX_VALUE case Int(x) = x case _ = throw ... } 目标是如果字符串等于“inf”,则
我正在寻找一种匹配可能包含整数值的字符串的方法。如果是这样,解析它。我想编写类似于以下内容的代码:
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... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |