Reputation: 77
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!
Upvotes: 0
Views: 4228
Reputation: 931
in Kotlin you can init variable in two ways.
in your case you don't user lateinit So, you need to init your variable with a default value
var test = Catalog()
or if you want to init as null
var test:Catalog? = null
Upvotes: 1
Reputation: 16214
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:
List
is immutable so you can't use the operator []
to assign a valueTo solve it, you can use MutableList
instead of List
.
class Catalog {
val musicList = mutableListOf<Music>()
}
fun main(args: Array<String>) {
var test = Catalog()
test.musicList += Music("1")
}
Upvotes: 2