Home > front end >  vararg and extension function in kotlin
vararg and extension function in kotlin

Time:09-30

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

CodePudding user response:

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