Skip to workspace
Kotlin Lab

Working with data / Chapter 04

Import valid quantities

Use a nullable transformation when an invalid row may disappear.

The decision

A warehouse exports one requested quantity per text field. Import positive base-ten Int values in encounter order. The export is ASCII text. A valid field consists of decimal digits with an optional leading sign. Skip whitespace-padded, malformed, out-of-range and nonpositive fields.

Read the Kotlin

Trace one field before processing the row

Read the chain inside the lambda from left to right. For these ASCII fields, toIntOrNull() accepts a sign and leading zeroes, rejects surrounding spaces and returns null on Int overflow. The safe call skips the positivity check after a parse failure. For a parsed number, takeIf retains it only when the predicate is true.

listOf(" 6", "+06", "6", "-0").map { it.toIntOrNull() }
// [null, 6, 6, 0] before the positivity filter

Decide whether input positions survive

With map, one input always contributes one output position, even if the transformation produces null. With mapNotNull, the transform may contribute zero elements. Both keep the encounter order of the values they emit. A preview with blank cells and a list of accepted quantities therefore need different result shapes.

val cells = listOf("3", "oops", "7")
cells.map { it.toIntOrNull() }         // [3, null, 7]
cells.mapNotNull { it.toIntOrNull() }  // [3, 7]

Attach row numbers before dropping anything

A Kotlin list index starts at zero. A row number on a spreadsheet usually starts at one. Capture index + 1 while visiting each original field. If you first filter to invalid fields, their indices describe positions in the error list and can send a user to the wrong spreadsheet row.

val cells = listOf("8", "x", "?")
cells.mapIndexedNotNull { i, cell ->
    if (cell.toIntOrNull() == null) i + 1 else null
}  // [2, 3]

The full example

Java 25
import java.util.List;
import java.util.Optional;

class Lesson {
    static Optional<Integer> quantity(String field) {
        try {
            int n = Integer.parseInt(field);
            return n > 0 ? Optional.of(n) : Optional.empty();
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }

    static List<Integer> quantities(List<String> fields) {
        return fields.stream().map(Lesson::quantity)
            .flatMap(Optional::stream).toList();
    }
}
Kotlin/JVM
fun quantities(fields: List<String>): List<Int> =
    fields.mapNotNull { field ->
        field.toIntOrNull()?.takeIf { it > 0 }
    }

Inputs and outcomes

InputOutcomeWhy it matters
["02", "bad", "+3", "0"][2, 3]An invalid field disappears without shifting the order of valid values.
["2147483648", "-1"][]Neither overflow nor a negative number produces a quantity.

Walk through the code

  1. toIntOrNull turns invalid syntax and Int overflow into null. For a parsed Int, takeIf keeps it only when it is positive.
  2. mapNotNull appends each non-null transformation result in order. Java represents absence with Optional.empty and flattens each optional into a stream of zero or one value.

The Java habit

Using map with toIntOrNull preserves a null entry for each parse failure. Filtering the input strings for non-emptiness does not catch overflow or a field such as 2x.

When to choose differently

If an operator needs the line numbers and reasons for rejected rows, silently dropping them loses evidence. Return a per-row result carrying the error.

References

Open quizTry code