Scala FAQ: How do I convert a String to Int in Scala?
If you need to convert a String to Int in Scala, just use the toInt method which is available on String objects, like this:
scala> val i = "1".toInt i: Int = 1
As you can see, I just cast a String (the string "1") to an Int object using the toInt method on the String.
However, beware that this can fail just like it does in Java, with a NumberFormatException, like this:
scala> val i = "foo".toInt java.lang.NumberFormatException: For input string: "foo"
so you'll want to account for that in your code, such as with a try/catch statement.
As an example, the following toInt functions account for the exceptions that can be thrown in the String to Int conversion process. This first example shows the "Java" way to write a String to Int conversion function:
def toInt(s: String):Int = {
try {
s.toInt
} catch {
case e:Exception => 0
}
}
That function returns the Int value if the String is something that can be converted to an Int, such as "42", and returns 0 if the String is something else, like "foo".
A more "Scala like" way to write a String to Int conversion function looks like this:
def toInt(s: String):Option[Int] = {
try {
Some(s.toInt)
} catch {
case e:Exception => None
}
}
This function returns a Some(Int) if the String is successfully converted to an Int, and a None if the String could not be converted to an Int. This is shown in the following REPL examples:
scala> val x = toInt("foo")
x: Option[Int] = None
scala> val x = toInt("10")
x: Option[Int] = Some(10)
To get the value from the Some, you'll typically use the getOrElse method, like this:
scala> x.getOrElse(0) res0: Int = 10
Note: As I hinted at above, the toInt method really isn't on the String class. It's actually contained in a class named StringOps, which is bound to the String class using an implicit conversion in Scala. I describe this a little more in my How to show String and StringOps methods in the Scala REPL examples.
Post new comment