Reputation: 460
Suppose I have a data class Foo
with properties like:
field_1
field_2
....
field_10
An object of this class was created like
val foo = Foo(1, 2,...10)
For some reason I want to get access to properties using something like this:
//here is correct
val fieldNumber = someFunToCalculateFieldNumber()
val combinedFooField = "field_$fieldNumber"
//here is wrong
val value = foo.combinedFooField
Is there a way to do this?
Upvotes: 0
Views: 56
Reputation: 5707
you need to use Kotlin Reflection module
from :
https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-reflect/1.4.0-rc
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>1.4.0-rc</version>
<scope>runtime</scope>
</dependency>
then :
package org.example
data class Hello(val a: Int, val b: Int, val c: Int, val d: Int) {
fun getFields() = Hello::class.java.declaredFields.withIndex().map {
"${it.index},${it.value.name}"
}
}
fun main(args: Array<String>) {
val h = Hello(1,2,3,4)
for (field in h.getFields()) {
println(field)
}
}
Upvotes: 1