shi*_*eng 4 java scala number-formatting
在Java中,我可以使用以下两个语句将字符串转换为整数,这可以处理异常:
// we have some string s = "abc"
int num = 0;
try{ num = Integer.parseInt(s); } catch (NumberFormatException ex) {}
Run Code Online (Sandbox Code Playgroud)
但是,我在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)
Run Code Online (Sandbox Code Playgroud)
这是在Scala中将字符串转换为整数的唯一方法(能够处理异常)还是有更简洁的方法?
elm*_*elm 12
考虑
util.Try(s.toInt).getOrElse(0)
Run Code Online (Sandbox Code Playgroud)
这将提供整数值,同时捕获可能的异常.从而,
def toInt(s: String): Int = util.Try(s.toInt).getOrElse(0)
Run Code Online (Sandbox Code Playgroud)
或者如果Option是首选,
def toInt(s: String): Option[Int] = util.Try(s.toInt).toOption
Run Code Online (Sandbox Code Playgroud)
其中,None如果转换失败交付.