Thursday 8 December 2022

Null handling in Kotlin

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:

// always has a value:
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 person: Person? = getPerson()
val name: String? = person?.name

Using let:

person?.name?.let{ println(it) }

Default values:

person?.name?:"Mrbear"

Throwing an exception if it's not there:

person?.name?:return null
person?.name?:throw NullPointerException("name is not there")

And then there's !!, for those who know what they're doing:

val now: LocalDate = LocalDate.now()!!

Safe casts if the cast is unsuccesfull:

val aInt: Int? = a as? Int

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

No comments:

Post a Comment