Daltrey Waters
Daltrey Waters

Reputation: 415

How to use the eivls operator with a nullable lambda parameter?

I have a function with a nullable lambda parameter defined as -

fun download_a_file(callback_after_download_is_complete: (() -> Any)? = null)
    {
        // ... do things ...
    }

The idea is that after the file is downloaded, whoever is calling the function can pass a lambda function to execute some code after the file is downloaded.

The parameter is null since someone may not wish to have a lambda post download.

So inside the download_a_file function I have this code -

if( callback_after_download_is_complete != null)
    callback_after_download_is_complete()

Which works, but isn't elegant. I'd rather use a elvis operator here, if I can. However I'm not finding any good references on how to call a nullable lambda parameter with the elvis operator. Can you do that? if so - how?

Upvotes: 0

Views: 335

Answers (1)

Daniel
Daniel

Reputation: 2554

If you notice, you cannot call an anonymous nullable function directly:

Reference has a nullable type '(() -> Any)?', use explicit '?.invoke()' to make a function-like call instead

So all you have to do is use invoke/0:

fun download_a_file(callback_after_download_is_complete: (() -> Any)? = null) {
  callback_after_download_is_complete?.invoke()
}

Upvotes: 3

Related Questions