Scala FAQ: How do I convert a String
to Int
in Scala?
Solution: Use ‘toInt’
When you need to convert a String
to an Int
in Scala, 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
. But...
Caution
However, beware that this can fail with a NumberFormatException
just like it does in Java:
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 Scala try
/catch
statement.
A Java-like 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 { s.toInt } 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".
When I say that this function uses a Java-like approach, please note that I originally wrote this article before Java had the
Optional
type.
A Scala “String to Int” conversion function that uses Option
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 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)
As I wrote in my book about Scala and functional programming, you can also write a Scala toInt
function that uses Try
, Success
, and Failure
like this:
import scala.util.{Try, Success, Failure} def makeInt(s: String): Try[Int] = Try(s.trim.toInt)
You can also return an Option
like this:
import scala.util.control.Exception._ def makeInt(s: String): Option[Int] = allCatch.opt(s.toInt)
Please see my Scala Option/Some/None idiom tutorial for more ways to use these patterns, and to use the Option
and Try
results.
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
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.