0

How to get the copy of arraylist of sealed class in android

private var homePageApiResponseList : ArrayList<HomeApiResponseModel> = ArrayList()

Here HomeApiResponseModel is a Sealed class. HomeApiResponseModel is given as Below

sealed class HomeApiResponseModel {

    data class HomeCategoryListModel(
        var categoryList : MutableList<CategoryModel> = mutableListOf(),
        var categoryNameType : String = ""
    ) : HomeApiResponseModel()

    data class HomeBestSellerListModel(
        var bestSellerList : MutableList<ChildrenModel> = mutableListOf(),
        var bestSellerNameType : String = ""
    ) : HomeApiResponseModel()

    data class HomeMustTryListModel(
        var mustTryList : MutableList<ChildrenModel> = mutableListOf(),
        var mustTryNameType : String = ""
    ) : HomeApiResponseModel()
}

Normally arraylist of object copy is easly obtain by anyList.map { it.copy() }

While in sealed class it shows error. How to get a copy of arraylist of sealed class

Thanks

1 Answers1

0

Create an abstract function in the parent. Each child can implement it and call through to their own copy(). The abstract function should have a different name than “copy” to avoid conflicts.

By the way, in your case, a sealed interface is probably a cleaner choice than a sealed class because there is no common functionality between the children. And I suggest avoiding combining mutable collections with var properties. Making something mutable in two different ways adds (usually unnecessary) complexity and more opportunities for bugs.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154