Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null safety operator for function variable in Kotlin

In my Kotlin app I have nullable variable like this

private var myCallback : (() -> Unit)? = null

Is it possible to use null safety operator ? to call it? This gives me a compilation error.

myCallback?()

I found only this ugly way for a call if it is not null

 if(myCallback != null)
     myCallback!!()
like image 246
Vitalii Avatar asked Oct 22 '25 01:10

Vitalii


1 Answers

You can call it as follows:

 myCallback?.invoke()

The () syntax on variables of function types is simply syntax sugar for the invoke() operator, which can be called using the regular safe call syntax if you expand it.

like image 90
yole Avatar answered Oct 25 '25 01:10

yole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!