0
val a = 5
println("a $a") // instead of this, we can call foo(a)

Calling println("a $a") many times is suffer. Can we create a new function and just call foo(a)?

omega1100100
  • 39
  • 1
  • 6
  • @deHaar oh sorry, that's my bad!!! – omega1100100 Dec 20 '19 at 10:20
  • @deHaar I want to create a new function `fun foo(a: Any)` that print it's argument name and value. Like `foo(a)` will print `a 5`. – omega1100100 Dec 20 '19 at 10:25
  • Does this answer your question? [Is there a way in Java to find the name of the variable that was passed to a function?](https://stackoverflow.com/questions/9984550/is-there-a-way-in-java-to-find-the-name-of-the-variable-that-was-passed-to-a-fun) – GvS Dec 20 '19 at 10:27

1 Answers1

0

It is not easily / directly possible (at the moment)...

Consider your fun, you would have to do it with the following syntax:

fun foo(a: Any) {
    println("'${::a.name}' : $a") // doesn't compile
}

Unfortunately, this feature is currently only available for properties and function names, but not for local variables (yet), according to this discussion and according to the most recent Kotlin Eclipse Plugin, because it shows me

enter image description here

Read the mentioned discussion and this question in order to find possible alternatives and more information in general.

deHaar
  • 17,687
  • 10
  • 38
  • 51
  • Even if it were possible, it wouldn't help in this case; I assume that for the call `val x = 3; foo(x)` the asker wants to print `x : 3`, but using `::a.name` would print `a : 3`. – Alexey Romanov Dec 20 '19 at 13:31
  • @AlexeyRomanov Yes, you are right... This is not a very good example of what is not working. I don't know if any reflection might work... – deHaar Dec 20 '19 at 13:33