Bri*_*hon 4 scala pattern-matching
我试图找出模式匹配Scala中int的字符串表示的最佳方法.我真正想要做的是这样的事情:
"1234" match {
// Some cases
case "five" => 5
case Int(i) => i // Fails
case _ => throw new RuntimeException()
}
Run Code Online (Sandbox Code Playgroud)
一种方法是使用正则表达式.一个潜在的问题是它不会检测整数是否太大而不适合int.
val ISINT = "^([+-]?\\d+)$".r
"1234" match {
case "five" => 5
case ISINT(t) => t.toInt
case _ => throw new RuntimeException()
}
Run Code Online (Sandbox Code Playgroud)
另一种方法使用toInt返回的函数Option(从这篇博文中借用).这很好,因为它使标准库弄清楚字符串是否包含整数.问题在于它迫使我将逻辑嵌套在我认为它应该是平坦的地方.
def toInt(s: String): Option[Int] = {
try {
Some(s.toInt)
} catch {
case e: Exception => None
}
}
"1234" match {
case "five" => 5
case t => toInt(t) match {
case Some(i) => i
case None => throw new RuntimeException()
}
}
Run Code Online (Sandbox Code Playgroud)
您可以像这样定义自定义提取器
object Int {
def unapply(s: String): Option[Int] = util.Try(s.toInt).toOption
}
Run Code Online (Sandbox Code Playgroud)
并按照您的意愿使用它
"1234" match {
// Some cases
case "five" => 5
case Int(i) => i // works :)
case _ => throw new RuntimeException()
}
Run Code Online (Sandbox Code Playgroud)