Kotlin扩展函数使用vararg参数时设置默认值为null报错的问题求助
Hey there! Let's break down what's going wrong here and how to fix it quickly.
The Root of the Problem
The error you're seeing happens because vararg parameters in Kotlin are treated as non-null Array<out T> types, and you're trying to set null as the default value. Since Array<out () -> Unit> can't be null, the compiler throws that red flag at you.
Luckily, you don't even need that null default—vararg parameters already support being called with no arguments, and the compiler automatically passes an empty array in that case.
Solution 1: Remove the Null Default Value
Just drop the = null from your function definition. Here's the corrected code:
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 perfectly because:
- When you call
applyWithUserParameters()without any arguments,functionListwill be an empty array, so the loop does nothing (which is exactly what you wanted with the null default). - You can still pass one or more lambda functions as arguments, like this:
val analyticsBundle = Bundle().applyWithUserParameters( { putString("screen_name", "home") }, { putLong("session_duration", 120000) } )
Solution 2: Explicitly Use an Empty Array as Default (Optional)
If you prefer to make the default behavior explicit, you can set the default to an empty array instead of null:
fun Bundle.applyWithUserParameters(vararg functionList: () -> Unit = emptyArray()): Bundle = Bundle().apply { // ... rest of your code }
This achieves the same result as Solution 1, it's just a more verbose way to write the default.
Why Your Original Code Failed
In Kotlin, when you use vararg, the compiler converts the passed arguments into an array of the specified type. Since your lambda type () -> Unit is non-null, the resulting array Array<out () -> Unit> is also non-null. Assigning null to this non-null type violates Kotlin's null safety rules, hence the error.
内容的提问来源于stack exchange,提问作者Kratos

