Hello! Recently I was having a discussion here about null coalescing operators used on a nullable property, and it brought up some strange behavior with regards to assignments/declarations.
(Note: I’ve never had an issue with this in my own code, just an interesting case.)
if I set up everything like this, with the goal of using primary.id or else alt.id or else null:
class Test(val id: String? = null) var primary: Test? = null primary = Test() var alt: Test? = null alt = Test("alternate")
This works as expected:
var id: String? = null id = primary?.id ?: alt?.id println(id) // prints "alternate"
But if the id is set in the declaration no dice:
var id: String? = primary?.id ?: alt?.id println(id) // always prints "null" (id property of primary)
Same deal with an if statement:
// Always null var id: String? = if (primary?.id != null) primary!!.id else alt?.id // Works as intended var id: String? = null id = if (primary?.id != null) primary!!.id else alt?.id
The difference seems to be caused by whether something is an assignment or an expression, I’m curious about what is going on under the hood here.