In Kotlin, is it possible to use a variable to call a method or property?

烈酒焚心 提交于 2019-12-08 07:04:26

问题


Simply put, I have a variable that tells me which property I need to modify on an object, but cannot call that property AS the variable.

data class MyDataClass(var one: String, var two: Int)

fun doSomething() {
    myData = MyDataClass("first", 2)

    val propertyImInterestedIn = "one"

    myData.{propertyImInterestedIn} = "second" // How do I do this?

    assertEquals("second", myData.one)
}

回答1:


You can either do it at compile time if You can directly reference the fields, or at runtime but you will lose compile-time safety:

// by referencing KProperty directly (compile-time safety, does not require kotlin-reflect.jar)
val myData = MyDataClass("first", 2)
val prop = myData::one
prop.set("second")

// by reflection (executed at runtime - not safe, requires kotlin-reflect.jar)
val myData2 = MyDataClass("first", 2)
val reflectProp = myData::class.memberProperties.find { it.name == "one" }
if(reflectProp is KMutableProperty<*>) {
    reflectProp.setter.call(myData2, "second")
}



回答2:


You can use the Kotlin reflection API to do that, and bound callable references in particular:

val propertyImInterestedIn = myData::one
propertyImInterestedIn.set("second")

Note that you need to add kotlin-reflect as a dependency to your project.



来源:https://stackoverflow.com/questions/51715815/in-kotlin-is-it-possible-to-use-a-variable-to-call-a-method-or-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!