Scala: How to convert a String to an Int (Integer)

Scala FAQ: How do I convert a String to Int in Scala?

Back to top

Solution: Use 'toInt()'

If you need to convert a String to an 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 the string "1" to an Int object using the toInt method, which is available to any String.

However, beware that this can fail with a NumberFormatException just like it does in Java, 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.

Back to top

A “Java” String to Int conversion function

The following functions show a couple of ways you can handle the exception 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 {
  } catch {
    case e: Exception => 0

That function returns the correct int value if the string can be converted to an int (such as "42"), and returns 0 if the string is something else, like the string "foo".

Back to top

A “Scala” String to Int conversion function

A more "Scala like" way to write a string to int conversion function looks like this:

def toInt(s: String): Option[Int] = {
  try {
  } 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 integer. This function 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)

One way to get the value from the Some is to use the getOrElse method:

scala> x.getOrElse(0)
res0: Int = 10

Please see my Scala Option/Some/None idiom tutorial for other and better ways to use this pattern.

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.

Back to top

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.