In Kotlin, is it possible to use a variable to cal

2019-05-31 19:37发布

问题:

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.