0

I am trying to write extension function in kotlin. I came almost to the end but one simple thing stopped me. Code goes like this:

fun Bundle.applyWithUserParameters(vararg functionList: () -> Unit = null): Bundle = Bundle().apply {
for (method in functionList)
    method()
FirebaseAnalyticsHelper.clientRepository.getClientData()?.clientID?.let {
    putInt(
        FirebaseAnalyticsHelper.KEY_USER_ID, it
    )
}
}

null is underlined and it says: "Null can not be a value of a non-null type Array<out () -> Unit>"

Is there any way to fix this or I am unable to use vararg at all in this case? Thanks

7
  • You seem to be setting the default value of the varargs parameter to null. That doesn't make much sense. Why do you want to do that? Commented Sep 29, 2021 at 9:10
  • Because in some cases I will send 2,3,4 functions as arguments and in some cases, I will send zero arguments to applyWithUserParameters Commented Sep 29, 2021 at 9:19
  • So...? Why does that mean you need = null? A vararg, by itself, without a default value, can take 0 or more arguments. How about removing = null? Commented Sep 29, 2021 at 9:22
  • Can you please write that down, how would it look? bundle. applyWithUserParameters....? Commented Sep 29, 2021 at 9:27
  • How would what look? Commented Sep 29, 2021 at 9:28

1 Answer 1

3

You seem to be trying to set the default value of the varargs parameter to null. This is not needed. Varargs can take 0 parameters, even without a default value.

fun Bundle.applyWithUserParameters(vararg functionList: () -> Unit): Bundle = 
    Bundle().apply {
        for (method in functionList)
            method()
        FirebaseAnalyticsHelper.clientRepository.getClientData()?.clientID?.let {
            putInt(
                FirebaseAnalyticsHelper.KEY_USER_ID, it
            )
       }
    }

This works:

someBundle.applyWithUserParameters()
Sign up to request clarification or add additional context in comments.

1 Comment

True that! I didn't know the fact that vararg takes 0 parameters even without default value when you write it with empty brackets. Thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.