Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

2d mutable list populate – kotlin

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)
        } 
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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") }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading