简体   繁体   English

如何获得 ArrayList 的副本<sealed class>在 android 使用 kotlin</sealed>

[英]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 android中封存的class的arraylist副本如何获取

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

Here HomeApiResponseModel is a Sealed class. HomeApiResponseModel is given as Below这里的 HomeApiResponseModel 是一个 Sealed class。HomeApiResponseModel 给出如下

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() }通常 object 副本的 arraylist 很容易通过anyList.map { it.copy() }

While in sealed class it shows error.在密封的 class 中显示错误。 How to get a copy of arraylist of sealed class如何获得密封class的arraylist副本

Thanks谢谢

Create an abstract function in the parent.在父类中创建一个摘要 function。 Each child can implement it and call through to their own copy() .每个孩子都可以实现它并调用他们自己的copy() The abstract function should have a different name than “copy” to avoid conflicts.摘要 function 的名称应与“copy”不同,以避免冲突。

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.顺便说一句,在您的情况下,密封接口可能比密封 class 更干净,因为子级之间没有共同的功能。 And I suggest avoiding combining mutable collections with var properties.我建议避免将可变 collections 与var属性结合使用。 Making something mutable in two different ways adds (usually unnecessary) complexity and more opportunities for bugs.以两种不同的方式使某些东西可变会增加(通常是不必要的)复杂性和更多出现错误的机会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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