jeudi 28 juillet 2022

Access Kotlin Interface/Class property by string key?

I need to access a class instance property similar to accessing a map in Kotlin.

For a map it goes like this

val myMap: Map<String, String> = mapOf("foo" to "bar")
assertThat(myMap["foo"]).isEqualTo("bar"

Now I want something similar to a class

data class House(
  val street: String
)

// pseudo code wish
fun foo() {
  val valueOfFoo: String = House::class.members["foo"].callGet()
}

I read into reflection but can't find a way to call it. I know the problem somewhat is that there is no class instance passed or specified. However I wonder if there is such thing?

val house = House("Baker Street 5")
val valueOfFoo: String = House::class.members["foo"].callGetWithInstance(house)
   
assertThat(valueOfFoo).isEqualTo("Baker Street 5")




Aucun commentaire:

Enregistrer un commentaire