Home > Software engineering >  2d mutable list populate - kotlin
2d mutable list populate - kotlin

Time:06-29

I am trying to fill the list below with strings, but I cannot figure out how to set the variable strings to match the required type. I keep getting type mismatch. (type mismatch: inferred type is MutableList but String was expected)

fun main() {
        val inputList: MutableList<MutableList<String>> = mutableListOf()
        val n = readLine()!!.toInt()
        var strings: String 
            
        for (i in 0 until n) {
            strings = "D".toString().toMutableList()
            inputList.add(strings)
        } 
    }

CodePudding user response:

inputList is a list of lists. So you can only add lists to it. You defined strings as type String but you actually want it to be MutableList<String>. Furthermore, the toString() is useless because "D" is already a String, and also toMutableList turns a String into a MutableList<Char> of its characters. So what you want to do is:

val inputList: MutableList<MutableList<String>> = mutableListOf()
val n = readLine()!!.toInt()
var strings: MutableList<String>

for (i in 0 until n) {
    strings = mutableListOf("D")
    inputList.add(strings)
} 

Though I would say it's unnecessary to first store it in strings so you can just do

val inputList: MutableList<MutableList<String>> = mutableListOf()
val n = readLine()!!.toInt()

for (i in 0 until n) {
    inputList.add(mutableListOf("D"))
}

or you can get the same result much shorter with

val n = readLine()!!.toInt()
val inputList = MutableList(n) { mutableListOf("D") }
  • Related