Lesson contents

Kotlin — Validating input with nullable Int

Kotlin can use Int? to represent a valid seat number or null. Check both the numeric conversion and the allowed seat range before accepting the input.

A simple example

Turn text into a number

  1. Start with "2"
  2. Do this Read an integer, add 1
  3. Result 3
The conversion produces the number 2. Adding one now gives 3.
Lesson.kt
fun main() {
    val n = "2".toIntOrNull()
    if (n != null) println(n + 1)
}
Output
3
Advertisements

Validate a seat number

Int? permits null. Safe calls stop the chain if a prior check failed. toIntOrNull also handles numeric overflow, while the final takeIf enforces the business rule.

Seat 3: Accept. Seat 0: Out of range. Seat x: Invalid number.
Validate a seat request

A minibus has seats numbered 1 to 8. A passenger entering 3 can be assigned that seat. Zero is numeric but outside the seating plan, and x cannot be read as a whole seat number.

Run the example

Kotlin/JVM. Run these commands from the directory containing the example.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Lesson.kt
fun seatNumber(text: String): Int? =
    text.takeIf { it.matches(Regex("[0-9]+")) }
        ?.toIntOrNull()
        ?.takeIf { it in 1..8 }

fun main() {
    for (text in listOf("3", "0", "x")) {
        println(seatNumber(text)?.toString() ?: "invalid")
    }
}
Output
3
invalid
invalid

Only whole-number seat labels from 1 through 8 are accepted. The text 3 passes both checks. Zero parses but is outside the range. The letter x does not represent a decimal seat number.

Try it yourself

Predict the results for 8, 9, and an empty string.

Check your answer

Only 8 is accepted. Nine is outside the range and an empty string has no digits. The existing loop can continue after either rejection.

Kotlin language documentation

Related tags

  • Kotlin
  • validation
  • errors
  • optional values