简体   繁体   中英

How to get copy of the ArrayList<Sealed Class> in android using kotlin

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM