Just some notes, as I find myself forgetting the Null-safety features of Kotlin.
Actually, most of the text in this blog is basically already written in [1], so you might want to check there as well.
So, there are three possibiltiies:
val name: String = "Mrbear"
// sometimes has a value:
val sometimesName: String? = null
// function in java, so no clue what it might be:
val date = LocalDate.now()
// the return value shows up in IntelliJ hints as LocalDate!
You can use if statements, of course, to check for nulls.
Sometimes this doesn't work, because it might be mutable, see [2].
Safe calls can be used, like so for example when person might be null:
val name: String? = person?.name
Using let:
Default values:
Throwing an exception if it's not there:
person?.name?:throw NullPointerException("name is not there")
And then there's !!, for those who know what they're doing:
Safe casts if the cast is unsuccesfull:
References
- [1] Kotlin - Null safety
- https://kotlinlang.org/docs/null-safety.html
- [2] Smart cast to 'Type' is impossible, because 'x' is a mutable property that could have been changed by this time
- http://randomthoughtsonjavaprogramming.blogspot.com/2022/09/smart-cast-to-type-is-impossible.html