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

风格不统一 提交于 2019-12-07 03:34:17

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

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.

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