Search code examples
kotlinoperator-keywordnullable

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?


Solution

  • 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()
    }