Kotlin中填充二维可变列表(MutableList<MutableList<String>>)时遭遇类型不匹配问题求助
Fixing the Type Mismatch in Your 2D Mutable List
Let's break down exactly why you're hitting that type mismatch error, and how to fix it quickly.
First, your inputList is declared as MutableList<MutableList<String>>—this means every element you add to it needs to be a list of strings. But right now, two things are off in your code:
- You declared
var strings: String, but you're trying to assign a list to it (that's a mismatch right there). - When you do
strings = "D".toString().toMutableList(), you're turning the string "D" into aMutableList<Char>(sincetoMutableList()on a String splits it into individual characters), not a list containing the string itself.
Here's the straightforward fix:
- Update the type of
stringsto match what you actually need:MutableList<String> - Instead of converting the string to a char list, create a mutable list that holds the string "D" directly using
mutableListOf("D")
Your corrected code will look like this:
fun main() { val inputList: MutableList<MutableList<String>> = mutableListOf() val n = readLine()!!.toInt() var strings: MutableList<String> // Fixed the variable type here for (i in 0 until n) { strings = mutableListOf("D") // Creates a list containing the string "D" inputList.add(strings) } }
This works because mutableListOf("D") creates a MutableList<String> with exactly one element (the string "D"), which perfectly matches the type your outer inputList expects.
内容的提问来源于stack exchange,提问作者sievy
相关产品推荐
相关产品推荐

