kwroot
kwroot

Reputation: 77

'Var' must be initialized Kotlin

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

Answers (2)

Chirag Bhuva
Chirag Bhuva

Reputation: 931

in Kotlin you can init variable in two ways.

  1. init with default value like... var temp:String = ""
  2. init with lateinit keyword(means you will init later) like... lateinit var temp:String

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

Giorgio Antonioli
Giorgio Antonioli

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:

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

Upvotes: 2

Related Questions