无法在 Kotlin 中更新 pojo class

Unable to update pojo class in Kotlin

我试图在 Kotlin 中的特定点击更新我的 pojo class,但它给我错误 :-

java.lang.Whosebugerror: stack size 8mb

这是我的 Pojo Class

class NavDrawerItem(var icon_normal: Int,var icon_notified: Int, var title: String, var isShowNotify: Boolean){
    var title1: String = title
        //  get() = title                    // Calls the getter recursively
        set(value)
        { title1 = value }

    var image: Int = icon_normal
        // get() = image
        set(value)
        { image = value }

    var image_notified: Int = icon_notified
        // get() = image
        set(value)
        { image_notified = value }


    var notify: Boolean = isShowNotify
        set(value) {
            notify = value
        }
}

我正在点击 NavigationDrawer 的 Item 更新我的 Pojo

override fun onItemClick(position: Int) {
        mDrawerLayout?.closeDrawer(this!!.containerView!!)
        position1 = position
        for (i in navDrawerItems.indices) {
            val item = navDrawerItems[i]
            item.notify=(if (i == position) true else false)
            navDrawerItems[i] = item
            mAdapter?.notifyDataSetChanged()
        }
    }

请帮帮我!!!

您的设置器创建无限循环,导致 WhosebugError 异常。

class NavDrawerItem(var icon_normal: Int,var icon_notified: Int, var title: String, var isShowNotify: Boolean){
    var title1: String = title
        //  get() = title                    // Calls the getter recursively
        set(value)
        { field = value }

    var image: Int = icon_normal
        // get() = image
        set(value)
        { field = value }

    var image_notified: Int = icon_notified
        // get() = image
        set(value)
        { field = value }


    var notify: Boolean = isShowNotify
        set(value) {
            field = value
        }
}

以上是设置字段,您的实现是在其中递归设置值。

此外,正如 ADM 提到的,最好将 notifyDataSetChanged 移到循环之外,而不是在每次迭代时更新。

将您的 class 修改为简单的 data class

data class NavDrawerItem(var icon_normal: Int,var icon_notified: Int, var title: String, var isShowNotify: Boolean)

override fun onItemClick(position: Int) {
    mDrawerLayout?.closeDrawer(this!!.containerView!!)
    for (i in navDrawerItems.indices) {
        val item = navDrawerItems[i]
        item.notify=(i == position)
    }
    mAdapter?.notifyDataSetChanged()
}

始终建议使用 data classes 来定义 pojo。 因为dataclasses只是为了存储数据而制作的。
在 kotlin 中,它们提供了许多比普通 class 更独特的功能。
例如,您不需要定义 setter 和 getter,它们会自动添加到您的数据中 class。
此外,您的数据 class 将自动覆盖一些有用的函数,例如 equalshashCodetoString,等等

定义数据class非常简单。

data class Foo ( val title : String, val isHungry : Boolean ){

}