Kotlin return 在其方法中返回 class 实例

Kotlin return back class instance in its method

我正在尝试制作一个 class 方法,修改它的实例并将其返回。

class OUser {
    var name = ""
    var car = ""
    var city = ""


    operator fun get(param: String): String {
        return this[param]
    }


    operator fun set(param: String, value: String) {
        this[param] = value
    }


    fun fromData(data: HashMap<String, String>): OUser {
        this::class.declaredMemberProperties.forEach {
            this[it.name] =  data[it.name]
        }
        return this
    }
}

但这会导致无限循环调用自身。

我们的想法是让 class 以这种方式工作成为可能:

val data = hashMapOf<String, String>( "name" to "Alex", "car" to "BMW", "city" to "New York" )
val info: OUser = OUser().fromData(data)

val param = "name"
val name = info[param]
info[param] = "Bob"

使这种行为成为可能的正确方法是什么?

我要说的是,当您拥有 public var.

等属性时,我不知道为什么您想要这样的行为

,为了使这种行为成为可能,解决方案比你的复杂得多,因为 operator fun 都应该访问 class 属性.

我发表的评论将(希望)说明一切:

class OUser {
    var name = ""
    var car = ""
    var city = ""

    // Cache the mutable String properties of this class to access them faster after.
    private val properties by lazy {
        this::class.declaredMemberProperties
            // We only care about mutable String properties.
            .filterIsInstance<KMutableProperty1<OUser, String>>()
            // Map the property name to the property.
            .map { property -> property.name to property }
            .toMap()
    }

    operator fun get(param: String): String = properties.getValue(param).get(this)

    operator fun set(param: String, value: String) {
        properties.getValue(param).set(this, value)
    }

    fun fromData(data: HashMap<String, String>): OUser = apply {
        data.forEach { (param, value) ->
            // Invoke the "operator fun set" on each key-pair.
            this[param] = value
        }
    }
}