Library contents

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

  1. Start with "12"
  2. Do this Read a base-ten integer
  3. Result 12
The characters 1 and 2 represent one ten and two ones. The resulting number can be used in arithmetic.

Syntax

Scala 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.

First output line0,42
Lesson.scala
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))
  }
}
Output
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

Advertisements

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?

Given“18” + 2 on hand
Worked result20

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?

Given“0” + 2 on hand
Worked result2