Nulls in collections in Kotlin
Parse messy input without a single try/catch.
fun main() {
val logged = listOf("12.4", "n/a", "9.8", "", "15.1")
// toDoubleOrNull turns bad input into null instead of throwing.
val parsed = logged.map { it.toDoubleOrNull() }
println(parsed)
// mapNotNull parses and drops the failures in one pass.
val depths = logged.mapNotNull { it.toDoubleOrNull() }
println("Mean of ${depths.size} readings: ${depths.average()}")
println("First good one: ${parsed.firstOrNull { it != null }}")
}
How it works
toDoubleOrNullmaps bad strings to null instead of exceptions.mapNotNulltransforms and drops the nulls in one pass.firstOrNullwith a predicate finds the first survivor, or null.
Keywords and builtins used here
funitmainval
The run, in numbers
- Lines
- 13
- Characters to type
- 440
- Tokens
- 98
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 84 seconds.
Step 3 of 3 in Null safety, step 18 of 27 in Language basics.