is there a better way to write this code? I'm not ...
# getting-started
d
is there a better way to write this code? I'm not a big fan of telling the compiler "fuck this null check, just trust me"
Copy code
get() {
            if (_fulfillmentDetails == null) {
                _fulfillmentDetails = FulfillmentDetails(this)
            }

            return _fulfillmentDetails!!
        }
d
return _fulfillmentDetails ?: FulfillmentDetails(this).also { _fulfillmentDetails = it }
d
thx
m
Also consider:
Copy code
val fulfillmentDetails by lazy {
    FulfillmentDetails(this)
}
https://kotlinlang.org/docs/reference/delegated-properties.html#lazy
💯 9
☝️ 2
d
your suggestion would imply to get rid of the backing field completely?
m
Yes, there would be no explicit backing field, it would be handled by the delegate. It's nearly identical to your code (except it may allocate another object and it is synchronized by default). You could use the "show kotlin bytecode" option in the IDE then decompile to get an idea of how it is actually implemented
There are ways to avoid the synchronization overhead, see the docs link I posted
d
i guess the main difference is that i can't check of null anymore without initiating the backing field. Right now I could do sth like if (_fulfillmentDetails == null) { do sth that should only happen if it was never accessed before }
m
True, if you need that sort of logic, the delegate may not be the best option for you.
d
okay, but thanks for the suggestion I have several places where this fits perfectly 😉
👍 1
d
Lazy exposes a function to check if it's initialized: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-lazy/is-initialized.html
💯 2
d
you never learn out, thx