how can I check for the nullability of a variable ...
# getting-started
o
how can I check for the nullability of a variable that should contain a function?
a
you mean check if its null and if not call it?
o
yea
the declaration itself, where does the
?
go?
var myFun: () -> Unit? = {}
?
a
(() -> Unit)?
you have to surround it with brackets
o
ahhh cleva
a
and to call it use
myFun?.invoke()
👍 1
o
yes
thank you
s
Depending on what you want, making it non nullable and supply an empty lambda
{}
for the null case might also be an option. I think it makes the code more readable in some situations.
o
that’s how it was
but then how will you check for emptyness?
or non-validity for a better term, so as to know when not to invoke it
a
depending on the underlying implementation, something like
if(myFun != { }) myFun()
could work, but nothing prevents you from accidentally invoking it. if its nullable, the compiler enforces that you check it first
o
yea it’s safer with a null check
s
Calling an empty lambda is the same as not calling it. It doesn't do anything. You don't have to check for emptyness. Furthermore, I wouldn't check if it's equal to an empty lambda, I don't even know if performing equality checks on lambdas work the way you expect. When you are guarding it with an if, i would definitely go for the null case.