In Java, I can convert a string to integer using two statements as follows, which is able to deal with the exception:
// we have some string s = "abc"
int num = 0;
try{ num = Integer.parseInt(s); } catch (NumberFormatException ex) {}
However, the methods I found in Scala always use the try-catch/match-getOrElse
approach like following, which consists several lines of codes and seems a little verbose.
// 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)
Is this the only way to convert string to integer in Scala (which is able to deal with exceptions) or is there a more concise way?
Consider
This will deliver an integer value while catching possible exceptions. Thus,
or in case an
Option
is preferred,where
None
is delivered if the conversion fails.