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

Kratos
  • 681
  • 1
  • 13
  • 30
  • 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? – Sweeper Sep 29 '21 at 09: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 – Kratos Sep 29 '21 at 09: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`? – Sweeper Sep 29 '21 at 09:22
  • Can you please write that down, how would it look? bundle. applyWithUserParameters....? – Kratos Sep 29 '21 at 09:27
  • How would _what_ look? – Sweeper Sep 29 '21 at 09:28
  • When I call this extension function from my code with zero arguments (in some other class). – Kratos Sep 29 '21 at 09:29
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/237630/discussion-between-sweeper-and-kratos). – Sweeper Sep 29 '21 at 09:30

1 Answers1

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()
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • 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 – Kratos Sep 29 '21 at 09:51