Alexey Simchenko
Alexey Simchenko

Reputation: 460

Get access to class.field_1 combining its property name with string "field_" and "1"

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

Answers (1)

Naor Tedgi
Naor Tedgi

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

Related Questions