Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most concise way to convert string to integer in Scala? [duplicate]

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?

like image 587
shihpeng Avatar asked Dec 11 '22 22:12

shihpeng


1 Answers

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.

like image 85
elm Avatar answered May 23 '23 10:05

elm