Scala - How to convert a String to an Int (Integer) | alvinalexander.com
By Alvin Alexander. Last updated: Jun 10, 2014 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. Scala String to Int conversion functions 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:Read full article from Scala - How to convert a String to an Int (Integer) | alvinalexander.com
No comments:
Post a Comment