Kotlin通用二传手功能

vdj*_*j4y 3 kotlin

我是科特林的新手。我想知道这是否可能

我希望创建一个函数,该函数将更改对象的属性值并返回对象本身。主要的好处是我可以链接此二传手。

class Person {
   var name:String? = null
   var age:Int? = null

   fun setter(propName:String, value:Any): Person{
      return this.apply {
          try {
              // the line below caused error
              this[propName] = value
          } catch(e:Exception){
              println(e.printStackTrace()) 
          }
      }
   }
}


//usage
var person = Person(null,null)
person
   .setter(name, "Baby")
   .setter(age, 20)
Run Code Online (Sandbox Code Playgroud)

但我收到错误消息“未知引用”

该问题被标记为重复,但是可能的重复问题专门是要更改“名称”的属性,但是我希望更改从函数传递给对象的anyProperty。似乎无法将两个问题联系起来。@Moira请提供解释它的答案。谢谢

Ale*_*nov 6

为什么不简化您的回答

fun setter(propName: String, value: Any): Person {
    val property = this::class.memberProperties.find { it.name == propName }
    when (property) {
        is KMutableProperty<*> ->
            property.setter.call(this, value)
        null -> 
            // no such property
        else ->
            // immutable property
    }
}
Run Code Online (Sandbox Code Playgroud)

不需要Java反射,它的唯一作用是停止支持非平凡的属性。

另外,如果您调用它operator fun set而不是fun setter

this[propName] = value
Run Code Online (Sandbox Code Playgroud)

可以使用语法来调用它。