Scala StringOps.toIntOption
toIntOption converts a string to Some(integer) when it represents an Int and to None when conversion fails.
A simple example
StringOps.toIntOption
- Start with "12"
- Do this Read a base-ten integer
- Result 12
Syntax
val parsed = text.toIntOption
Run this example in Scala
Save the program as Lesson.scala. Use Scala 2.13.
scalac Lesson.scala
scala Lesson
Parse numeric fields and retain a failure count
A shipment or sensor form accepts a number as text. Check both the allowed range and how much input was consumed so a partial number, invalid field or overflowing value cannot pass as a normal reading.
object Lesson {
def main(args: Array[String]): Unit = {
val fields = List("0", "42", "42kg", "2147483648")
val parsed = fields.map(_.toIntOption)
println(parsed.flatten.mkString(","))
println(parsed.count(_.isEmpty))
}
}
0,42 2
An input outside the Int range becomes None. Keeping the intermediate options lets the caller count rejected fields even when the final values are flattened.
Scala documentation for StringOps.toIntOption
Read the afternoon delivery
A store receives a quantity as text from a barcode reader. Read the whole decimal quantity and add it to the two units already at the desk. What total should the register show?
Read an empty delivery count
A class receives a stock record whose quantity field is the character zero. Read the whole decimal quantity and add it to the two units already at the desk. What total should the register show?