indee423
indee423

Reputation: 471

Add the Instance of the class to constructor parameter property

I have the following class structure. The CarModel Class has a defects List which is of Type CarDefects. And I wanted to add the instance of the CarDefects class into this list of defects of carModel which is passed as a parameter for the CarDefects constructor.
However i cannot the use the add method and the error message says the following: Unresolved reference: add

class CarModel(val brand: Brand, val modelName: String, val version: Int){
    var defects: List<CarDefects>? = null

    inner class Car(val model: CarModel, val manufactureYear: Int, val engineSerialNum: String){
    }
    inner class CarDefects(var carModel: CarModel, val affectedYears: Array<Int>, val defectCode: String ) {

  
            init{
                carModel.defects.add(//instance of this class)
            }
    }
}

Upvotes: 0

Views: 29

Answers (1)

Ionut
Ionut

Reputation: 919

You have a List as the type of defects. List is immutable, so you can't add more elements to it. You need to use a mutableList to be able to do this.

Here you have more info on this

A generic ordered collection of elements. Methods in this interface support only read-only access to the list; read/write access is supported through the MutableList interface.

Alternatively, you can try to create a new mutable List and add it each time, then convert to list. Something like this.

defects = defects?.toMutableList()?.add(//your car instance).toList()

Upvotes: 1

Related Questions