christophsturm
12/12/2022, 8:45 PMprivate var factory: DBConnectionFactory? = null
...
what is better the best way to avoid the !!
here?
if (factory != null)
return factory!!.getConnection()
factory?.getConnection()?.also { return it }
works, but looks obfuscated to me.Paul Griffith
12/12/2022, 8:49 PMfactory?.let { it.getConnection() }
but I prefer plain if null checks most of the time, even if I have to “pay” the cost of an extra variablechristophsturm
12/12/2022, 8:51 PMfactory?.let { return it.getConnection() }
is way better than my version 2, what was I thinking…christophsturm
12/12/2022, 8:53 PMalex.krupa
12/13/2022, 7:25 AMif
variant factory
can change between the null-check and the unsafe access, so there's risk of a NullPointerException
being thrown (e.g. when it's modified from different threads).
You can avoid it by assigning the reference locally:
val factory = factory
if (factory != null) {
return factory.getConnection() // factory will be non-null here
}
Zun
12/14/2022, 2:37 PMchristophsturm
12/14/2022, 2:45 PMsuspend
Riccardo Lippolis
12/18/2022, 6:37 PMlateinit var
? Then it doesn't need to be nullable anymore