Michael
Michael

Reputation: 42100

String to Int in Scala

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 ?

Upvotes: 2

Views: 6128

Answers (2)

elm
elm

Reputation: 20435

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

Upvotes: 4

Brian
Brian

Reputation: 20295

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)
}

Upvotes: 8

Related Questions