本文介绍了如何为mutableList编写设置器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这样做,但是没有用

I was trying to do this, but it did not work

var stringList = mutableListOf<String>()
    set(value) {
        field = value
        validateData()
    }

以某种方式validateData()无法运行

somehow validateData() did not run

推荐答案

它确实做到了.

我假设您真正想要的是每次在列表中添加或删除String时触发validateData.

I'm assuming that what you really want it's to trigger validateData each time a String is added or removed from your list.

您可以使用implementation by delegation [1]编写自定义列表. :

class MList(
    private val list: MutableList<String> = mutableListOf(),
    private val listener: () -> Unit
) : MutableList<String> by list {

    override fun add(element: String) =
        list.add(element).also { listener.invoke() }

    override fun remove(element: String) =
        list.remove(element).also { listener.invoke() }

    ...

}

并像这样使用它:

class Foo {

    var stringList = MList { validateData() } // Now each time stringList.add() is called validateData will be triggered

    private fun validateData(){ ... }

}

这篇关于如何为mutableList编写设置器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-12 03:31