1

I have the following data class intended for use in an Android application running Kotlin version 1.2.51:

data class Data(var a: ArrayList<String>, var b: String)

As you can see, a is an ArrayList. I want to append elements from another array into a. I've tried this:

itemsToAppend.forEach {
    Data.a.add(it)
}

However, Android Studio determines that a is an unresolved reference. How exactly does one append an item to such an ArrayList?

Thanks.

1
  • 3
    Why are you address a as a static field in the way Data.a ? Your a is a member field, and should be addressed as a Data().a or val data = Data(); data.a. Commented Jul 20, 2018 at 15:00

3 Answers 3

2

Data classes are not object classes. You will have to initialise them before you can use it

val d= Data(ArrayList(), "demo")
itemsToAppend.forEach {
    d.a.add(it)
}
Sign up to request clarification or add additional context in comments.

Comments

1

create an instance of Data:

var a: ArrayList<String> = arrayListOf()
var data = Data(a, "something")

and use data in your loop

Comments

1

If you want to access you list staticly do this:

data class D(var a: ArrayList<String>) { // a can't be used as D.a
   companion object {
      var ab: ArrayList<String> = ArrayList() // ab can be used as D.ab
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.