You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin扩展函数使用vararg参数时设置默认值为null报错的问题求助

Fixing the Null Error with Vararg in Your Kotlin Extension Function

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, functionList will 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 15:57:39