I’m not familiar with cpp and auto but I guess your code is the same as:
val controller = getController()
if(controller != null){
controller.do()
} else {
//controller ptr is null here and so you can't do ccontroller-stuff with it
}
If this is the case your code is similar to:
getController()
?.also { it.do() }
?: run{
// controller ptr is invalid here and outside if statement
}
And if controller.do
cannot return null
, it is also the same as:
getController()
?.also { it.do() }
?: run{
// controller ptr is invalid here and outside if statement
}
If on the other hand it does more checks, it would be the same as:
getController()
?.takeIf{ it.checkAlso() }
?.also { it.do() }
?: run{
// controller ptr is invalid here and outside if statement
}
or
getController()
?.takeUnless{ it.checkNot() }
?.also { it.do() }
?: run{
// controller ptr is invalid here and outside if statement
}
Note, I’m using also
, let
returns the result of the lambda (in this case controller.do()
).
This means that if you use let
and controller.do
returns null, you would execute run as well.
that being said, I often use when
:
when(val controller = getController()){
null -> {
//controller is accessible, but is evaluated to null, so you can't do controller-stuff with it.
}
else -> controller.do()
}
I use run
, such that you could execute a block.
If you can have a simple statement instead, just replace run
completely:
getController()
?.takeUnless{ it.checkNot() }
?.also { it.do() }
// controller ptr is invalid here and outside if statement
?: doSomething()
Or for when:
when(val controller = getController()){
null -> doSomething()
else -> controller.do()
}