Number Parsing in Scala
Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Scala.
import scala.util.Try
object NumberParsing {
def main(args: Array[String]): Unit = {
// With toDouble, we parse the string to a Double
val f = "1.234".toDouble
println(f)
// For parsing integers, we can use toInt
val i = "123".toInt
println(i)
// Scala doesn't have built-in hex parsing, but we can use Integer.parseInt
val d = Integer.parseInt("1c8", 16)
println(d)
// For unsigned integers, Scala doesn't have a direct equivalent
// We can use Long to represent larger numbers
val u = "789".toLong
println(u)
// toInt is a convenience method for basic base-10 int parsing
val k = "135".toInt
println(k)
// Parse functions throw exceptions on bad input
// We can use Try to handle potential errors
val result = Try("wat".toInt)
println(result) // prints Failure(java.lang.NumberFormatException: For input string: "wat")
}
}
To run the program, save it as NumberParsing.scala
and use scala
:
$ scala NumberParsing.scala
1.234
123
456
789
135
Failure(java.lang.NumberFormatException: For input string: "wat")
In Scala, we use methods like toDouble
, toInt
, and toLong
for parsing numbers from strings. These methods are available on string objects directly, which makes the syntax more concise compared to using separate functions.
For parsing hexadecimal numbers, we use Integer.parseInt
with a radix of 16. Scala doesn’t have a direct equivalent to Go’s ParseUint
, but we can use toLong
to handle larger numbers.
Error handling in Scala is typically done using Try
, Option
, or exceptions. In this example, we’ve used Try
to demonstrate how to handle potential parsing errors.
Next, we’ll look at another common parsing task: URLs.