Library contents

Kotlin toIntOrNull and mapNotNull

toIntOrNull parses an integer or returns null for invalid or out-of-range input. mapNotNull can omit failed conversions from a collection.

A simple example

toIntOrNull and mapNotNull

  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

Kotlin syntax
fields.mapNotNull { it.toIntOrNull() }
Run this example in Kotlin

Save the program as Lesson.kt. Use Kotlin 2.2 on the JVM.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Read only valid integer samples

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.

From the programval fields = listOf("0", "42", "42kg", "2147483648")
First output line0, 42
Lesson.kt
fun main() {
    val fields = listOf("0", "42", "42kg", "2147483648")
    val values = fields.mapNotNull { it.toIntOrNull() }
    println(values.joinToString())
    println(fields.size - values.size)
}
Output
0, 42
2

Zero is a valid result and survives the filter. The example deliberately discards failures. Keep each field with its parse result when callers need an error report.

Kotlin documentation for toIntOrNull and mapNotNull

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