Most concise way to convert string to integer in Scala?

In Java, I can convert a string to an integer using two operators as follows, which can deal with an exception:

// we have some string s = "abc"
int num = 0;
try{ num = Integer.parseInt(s); } catch (NumberFormatException ex) {}

      

However, the methods I've found in Scala always take an approach try-catch/match-getOrElse

like the following, which is a few lines of code 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 a string to an integer in Scala (which can deal with exceptions) or is there a more concise way?

+3


source to share


1 answer


Consider

util.Try(s.toInt).getOrElse(0)

      

This will result in an integer value when looking for possible exceptions. Thus,

def toInt(s: String): Int = util.Try(s.toInt).getOrElse(0)

      



or in case a Option

is preferred,

def toInt(s: String): Option[Int] = util.Try(s.toInt).toOption

      

where is None

supplied if conversion fails.

+11


source







All Articles