https://kotlinlang.org logo
Title
o

oday

10/14/2018, 11:16 AM
how can I check for the nullability of a variable that should contain a function?
a

Andreas Sinz

10/14/2018, 11:17 AM
you mean check if its null and if not call it?
o

oday

10/14/2018, 11:18 AM
yea
the declaration itself, where does the
?
go?
var myFun: () -> Unit? = {}
?
a

Andreas Sinz

10/14/2018, 11:18 AM
(() -> Unit)?
you have to surround it with brackets
o

oday

10/14/2018, 11:18 AM
ahhh cleva
a

Andreas Sinz

10/14/2018, 11:19 AM
and to call it use
myFun?.invoke()
👍 1
o

oday

10/14/2018, 11:19 AM
yes
thank you
s

SiebelsTim

10/14/2018, 11:23 AM
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

oday

10/14/2018, 11:25 AM
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

Andreas Sinz

10/14/2018, 11:31 AM
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

oday

10/14/2018, 11:32 AM
yea it’s safer with a null check
s

SiebelsTim

10/14/2018, 1:22 PM
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.