0

There are a lot of similar questions, but I still can't find out right answer. In Jawa square brackets works i think, but in Kotlin?

data class source (
val npk : Int = 0,
val name : String = "",
val coa : String = ""
)

fun main() {
  var sourceList : MutableList<source> = mutableListOf(source(1, "Uno", "one"),
                                                       source(2, "Dues", "two"),
                                                       source(3, "Tres", "three"))
   sourceList.forEach { source -> println(source.name)} // haw to use variable instead "name"?
      val variable = "name"
 //  sourceList.forEach { source -> println(source.$variable)} Is there construction like this possible in KOTLIN?
Zpaulis
  • 3
  • 2
  • 1
    "In Jawa square brackets works i think" -- no, sorry. "Is there construction like this possible in KOTLIN?" -- if you add `fun get(key: String) { ... }` to the `source` class, you could use `source[variable]`. Your `get()` function would be responsible for returning the appropriate property value given the supplied `key`. – CommonsWare Nov 04 '20 at 23:25
  • Does this answer your question? [Accessing dynamically to a Kotlin class property](https://stackoverflow.com/questions/54244998/accessing-dynamically-to-a-kotlin-class-property) – Adam Millerchip Nov 05 '20 at 00:23

1 Answers1

0

Without code changes on your class it's only possible via reflection API. Not usually recommended as it can be slower, and is more error prone.

See this answer for an example on how reflection can be used to achieve that : https://stackoverflow.com/a/35539628/3801327

I'd recommend you to go with the solution that CommonsWare suggested in the comment ( adding get operator ) instead

Rick Sanchez
  • 4,528
  • 2
  • 27
  • 53