在Java中,我可以使用以下两个语句将字符串转换为整数,这能够处理异常:
// we have some string s = "abc"
int num = 0;
try{ num = Integer.parseInt(s); } catch (NumberFormatException ex) {}
然而,我在Scala中找到的方法总是使用try-catch/match-getOrElse
的方式,像下面这样,其中包含几行代码,似乎有点冗长。
// First we have to define a method called "toInt" somewhere else
def toInt(s: String): Option[Int] = {
try{
Some(s.toInt)
} catch {
case e: NumberFormatException => None
}
}
// Then I can do the real conversion
val num = toInt(s).getOrElse(0)
这是在Scala中将字符串转换为整数的唯一方式(能够处理异常),还是有更简洁的方式?