Idiomatic work with nullable values in Kotlin: conversion and safe access
Hi! I recently started learning Kotlin after Java and can't get used to the strict nullable type system. I have several scenarios where I'm confused about how to properly handle null.
For example, I have a function that returns a nullable String? from the database. I need to:
1. Check if the value is not null
2. If not null, convert it to Int (parsing)
3. If parsing fails or the value is null — return 0
I wrote this code, but it looks terrible:
```kotlin
fun parseNullableInt(value: String?): Int {
if (value != null) {
return try {
value.toInt()
} catch (e: NumberFormatException) {
0
}
} else {
return 0
}
}
```
It works, but surely there is a more concise and idiomatic w