4

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!!()
Vitalii
  • 10,091
  • 18
  • 83
  • 151
  • 1
    Possible duplicate of [How do I idiomatically call a nullable lambda in Kotlin?](https://stackoverflow.com/questions/51733552/how-do-i-idiomatically-call-a-nullable-lambda-in-kotlin) – Alexey Soshin Aug 15 '18 at 20:09

1 Answers1

7

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.

yole
  • 92,896
  • 20
  • 260
  • 197