Kotlin在其方法中返回类实例

问题描述 投票:0回答:1

我正在尝试使用修改其实例并将其返回的方法来制作一个类。

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
    }
}

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

这个想法是使以这种方式与课堂合作成为可能:

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"

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

class kotlin instance
1个回答
1
投票

我将开始说,我不知道为什么当您拥有公共var这些属性时,为什么要这样一种行为。

表示,要使这种行为成为可能,解决方案要比您的解决方案复杂得多,因为operator fun都应访问类的属性。

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

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
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.