【发布时间】:2017-03-23 16:05:32
【问题描述】:
我正在尝试找出在 Scala 中模式匹配 int 的字符串表示的最佳方式。我真正想做的是这样的:
"1234" match {
// Some cases
case "five" => 5
case Int(i) => i // Fails
case _ => throw new RuntimeException()
}
一种方法是使用正则表达式。这样做的一个潜在问题是它不会检测整数是否太大而无法放入 int。
val ISINT = "^([+-]?\\d+)$".r
"1234" match {
case "five" => 5
case ISINT(t) => t.toInt
case _ => throw new RuntimeException()
}
另一种方法使用返回Option 的toInt 函数(借用自this blog post)。这很好,因为它使标准库确定字符串是否包含整数。问题是它迫使我将我的逻辑嵌套在我认为它应该平坦的地方。
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()
}
}
【问题讨论】:
-
这是一个您可能感兴趣的更普遍的问题:stackoverflow.com/questions/40607586/…