Most concise way to convert string to integer in Scala?

4k views Asked by At

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?

1

There are 1 answers

2
elm On BEST ANSWER

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.