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
util.Try(s.toInt).getOrElse(0)
This will deliver an integer value while catching possible exceptions. Thus,
def toInt(s: String): Int = util.Try(s.toInt).getOrElse(0)
or in case an Option is preferred,
def toInt(s: String): Option[Int] = util.Try(s.toInt).toOption
where None is delivered if the conversion fails.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With