after ```private var factory: DBConnectionFactory?...
# codereview
c
after
Copy code
private var factory: DBConnectionFactory? = null
...
what is better the best way to avoid the
!!
here?
Copy code
if (factory != null)
   return factory!!.getConnection()
Copy code
factory?.getConnection()?.also { return it }
works, but looks obfuscated to me.
p
you can do
factory?.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 variable
c
Copy code
factory?.let { return it.getConnection() }
is way better than my version 2, what was I thinking…
thanks, but you are right, i will also keep the if.
a
These 2 aren't the same. In the
if
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:
Copy code
val factory = factory
if (factory != null) {
    return factory.getConnection() // factory will be non-null here
}
z
Or consider rewriting your code so that your factory can not be null
c
this is just a lazy variable, it is null at the beginning and then it is set. but it can’t use lazy {} because the method is
suspend
r
if you know that the variable will not be accessed until it is lazily initialized, you could make it a
lateinit var
? Then it doesn't need to be nullable anymore