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
- Start with "12"
- Do this Read a base-ten integer
- Result 12
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.
fun main() {
val fields = listOf("0", "42", "42kg", "2147483648")
val values = fields.mapNotNull { it.toIntOrNull() }
println(values.joinToString())
println(fields.size - values.size)
}
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
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?