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

为何Kotlin的when语法无法为lateinit变量uploadImgsPath赋值?

Why does Logcat keep showing "lateinit property uploadImgsPath has not been initialized" & why isn't when setting its value?

Hey there, let's break down what's going wrong with your code and fix it!

First: The reason behind the lateinit error

You declared uploadImgsPath as a lateinit variable, which means it must be assigned a value before you try to use it anywhere. The problem is your when statement doesn't cover all possible scenarios where this variable needs to be set:

  • When the spinner first loads, you set its selection to 0. If that initial item is the "UnCategorized" entry you added (with an empty categoryDesignID), your when's "" branch only updates categoryDesignID—it never touches uploadImgsPath.
  • If you ever add a new category to your CategoryDesign list without updating the when statement, selecting that new item will leave uploadImgsPath unassigned.
  • If any part of your code tries to access uploadImgsPath before the user selects an item (or before the onItemSelected callback runs), it'll throw this uninitialized error immediately.

Second: Why when isn't setting the value

Your when statement only handles 4 specific categoryDesignID values ("", "ClothingDesign", "CommercialDesign", "LightingDesign"). It has no fallback for any other possible IDs. So if the selected item's ID doesn't match any of those, none of the when branches execute—leaving uploadImgsPath uninitialized.

Solutions to fix both issues

Here are a few practical fixes you can implement:

1. Add an else branch to your when statement

This ensures every possible categoryDesignID triggers an assignment to uploadImgsPath:

override fun onItemSelected(
    parent: AdapterView<*>?,
    view: View?,
    position: Int,
    id: Long
) {
    when (it.get(position).categoryDesignID) {
        "" -> {
            categoryDesignID = ""
            // Assign a default path for uncategorized items
            uploadImgsPath = mStorageRef.child("uploadedDesignImgs").child("Uncategorized")
            Toast.makeText(context,"Please choose a category",Toast.LENGTH_LONG).show()
        }
        "ClothingDesign" -> {
            uploadImgsPath = mStorageRef
                .child("uploadedDesignImgs")
                .child("ClothingDesign")
            categoryDesignID = "ClothingDesign"
        }
        "CommercialDesign" -> {
            uploadImgsPath = mStorageRef
                .child("uploadedDesignImgs")
                .child("CommercialDesign")
            categoryDesignID = "CommercialDesign"
        }
        "LightingDesign" -> {
            uploadImgsPath = mStorageRef
                .child("uploadedDesignImgs")
                .child("LightingDesign")
            categoryDesignID = "LightingDesign"
        }
        // Fallback for any unrecognized category ID
        else -> {
            uploadImgsPath = mStorageRef.child("uploadedDesignImgs").child("Default")
            categoryDesignID = "Default"
            Toast.makeText(context, "Unknown category - using default path", Toast.LENGTH_LONG).show()
        }
    }
}

2. Replace lateinit with nullable variables + defaults

If you can't guarantee uploadImgsPath will always be assigned before use, ditching lateinit for nullable types eliminates the uninitialized exception entirely:

companion object {
    var categoryDesignID: String = ""
    var uploadImgsPath: StorageReference? = null
}

When using this variable, handle the null case safely with the Elvis operator:

val targetPath = uploadImgsPath ?: mStorageRef.child("uploadedDesignImgs").child("Default")

3. Initialize uploadImgsPath upfront

Set a default value when declaring the variable so it's never uninitialized:

companion object {
    lateinit var categoryDesignID:String
    var uploadImgsPath: StorageReference = mStorageRef.child("uploadedDesignImgs").child("Default")
}

Your when statement will then just update the value when needed, instead of assigning it for the first time.


内容的提问来源于stack exchange,提问作者Squall Huang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:08:55