'Var' must be initialized Kotlin

kwroot :

Some of you can help me with this little problem? I'm very new to Kotlin and Android development! I don't understand why this snippet of code returns me the following error:

class Catalog {
var musicList: List<Music> = ArrayList()
}

class Music{
    var id: String = ""
}

fun main(args: Array<String>) {  
    var test: Catalog
    test.musicList[0] = "1"  
}

ERROR:

Variable 'test' must be initialized

What is wrong? Thank you all!

Giorgio Antonioli :

You need to instantiate it before invoking the getter of musicList:

fun main(args: Array<String>) {  
    var test = Catalog()
    test.musicList[0] = "1"  
}

Furthermore, if you are not re-assigning the value of test you can declare it as val:

fun main(args: Array<String>) {  
    val test = Catalog()
    test.musicList[0] = "1"  
}

You will have other 2 errors after that:

  1. since List is immutable so you can't use the operator [] to assign a value

To solve it, you can use MutableList instead of List.

class Catalog {
    val musicList = mutableListOf<Music>()
}
  1. You haven't an item at index 0 so you would get an out of bounds exception. To solve it, you can add your element:
fun main(args: Array<String>) {  
    var test = Catalog()
    test.musicList += Music("1")  
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=350303&siteId=1