2

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 ?

1
  • 2
    Other than using Try (@brian's answer), I would name the method toIntOption to be more in line with standard Scala names. Commented Feb 25, 2014 at 18:06

2 Answers 2

8

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)
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but I need to return Option now.
@Michael Use toOption.
Catch[+T].toOption ?
scala.util.Try("0".toInt).toOption or similarly scala.util.Try("foo".toInt).toOption will return Some(0) or None.
4

For getting an option in any case, regardless of possible exceptions due to number malformation,

import scala.util.Try

def toOptInt(s:String) = Try(s.toInt) toOption

Then

scala> toOptInt("123")
res2: Option[Int] = Some(123)

scala> toOptInt("1a23")
res3: Option[Int] = None

Further, consider

implicit class convertToOptInt(val s: String) extends AnyVal {
  def toOptInt() = Try(s.toInt) toOption
}

Hence

scala> "123".toOptInt
res5: Option[Int] = Some(123)

scala> "1a23".toOptInt
res6: Option[Int] = None

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.