Home > database >  Kotllin create an Arraylist of an Object
Kotllin create an Arraylist of an Object

Time:05-28

I want to create an array list of BaseObject getting the data from List< Allparkingquery> which has a same params as BaseObject but different class names

Here is the base BaseObject

 data class BaseObject (

    @SerializedName("queryfor") var queryfor : String,
    @SerializedName("whichitem") val whichitem : String,
    @SerializedName("Latitude") val latitude : String,
    @SerializedName("Longitude") val longitude : String,
    @SerializedName("DateCreated") val dateCreated : String,
    @SerializedName("NumberQueried") val numberQueried : String,
    @SerializedName("CurrentState") var currentState : String
)

Here is the array of @SerializedName("allparkingquery") val allparkingquery : List,

data class Allparkingquery (

    @SerializedName("queryfor") val queryfor : String,
    @SerializedName("whichitem") val whichitem : String,
    @SerializedName("Latitude") val latitude : String,
    @SerializedName("Longitude") val longitude : String,
    @SerializedName("DateCreated") val dateCreated : String,
    @SerializedName("NumberQueried") val numberQueried : String,
    @SerializedName("CurrentState") val currentState : String
)

Here is where am trying to loop List< Allparkingquery> as populate the data into List< BaseObject >

So the challange is baseList.add(item) is showing an error. See below

 var baseList: List<BaseObject> = ArrayList<BaseObject>()
            response.response_data.history[0].allparkingquery.forEachIndexed { index, item ->
                baseList.add(item)
            }

CodePudding user response:

The reason this is happening is that despite the similarities, BaseObject and Allparkingquery are not related as Allparkingquery does not inherit from BaseObject.

The justification for having a base object is lacking from your example so I'm assuming Allparkingquery will have a field that will differentiate it from BaseObject in the future, so going off that what you need to do is change BaseObject to an abstract class or an interface and have Allparkingquery inherit from it.

abstract class BaseObject {
    @SerializedName("queryfor") abstract var queryfor : String,
    @SerializedName("whichitem") abstract val whichitem : String,
    @SerializedName("Latitude") abstract val latitude : String,
    @SerializedName("Longitude") abstract val longitude : String,
    @SerializedName("DateCreated") abstract val dateCreated : String,
    @SerializedName("NumberQueried") abstract val numberQueried : String,
    @SerializedName("CurrentState") abstract var currentState : String
}

class Allparkingquery(
    override var queryfor : String,
    override val whichitem : String,
    override val latitude : String,
    override val longitude : String,
    override val dateCreated : String,
    override val numberQueried : String,
    override var currentState : String
) : BaseObject()
  • Related