String to Int in Scala
scala
Solution
I'd use `scala.util.Try` which returns `Success` or `Failure` for a computation that may throw an exception.
scala> val zero = "0"
zero: String = 0
scala> val foo = "foo"
foo: String = foo
scala> scala.util.Try(zero.toInt)
res5: scala.util.Try[Int] = Success(0)
scala> scala.util.Try(foo.toInt)
res6: scala.util.Try[Int] = Failure(java.lang.NumberFormatException: For input string: "foo")
So, `toMaybeInt(s: String)` becomes:
def toMaybeInt(s:String) = {
scala.util.Try(s.toInt)
}
Problem
Suppose I need to convert a String to Int in Scala. If the string is not a number I would like to return `None` rather than throw an exception. I found the following solution ``` def toMaybeInt(s:String) = { import scala.util.control.Exception._ catching(classOf[NumberFormatException]) opt s.toInt } ``` Does it make sense ? Would you change/improve it ?