0

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!

1
  • You didn't initialize test Commented Mar 22, 2020 at 17:48

2 Answers 2

2

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") } 
Sign up to request clarification or add additional context in comments.

Comments

1

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.