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. A Scala “String to Int” conversion function that uses OptionĪ more "Scala like" way to write a string to int conversion function looks like this: 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. 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". This first example shows the “Java” way to write a 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. A Java-like String to Int conversion function So you’ll want to account for that in your code, such as with a Scala try/ catch statement. However, beware that this can fail with a NumberFormatException just like it does in Java: If you need to convert a String to an Int in Scala, use the toInt method, which is available on String objects, like this:Īs you can see, I just cast the string "1" to an Int object using the toInt method, which is available to any String. Scala FAQ: How do I convert a String to Int in Scala? Solution: Use ‘toInt’ show more info on classes/objects in repl.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |