fun x(a: String) {
print(::a.name) // References to variables aren't supported yet.
}
val someVar = 1;
x(someVar) // ::a.name should be someVar
Is there a way to know the name of a property or a variable passed to the function by reflection?
e
Erik
01/30/2020, 7:38 AM
Maybe something like this could help you:
Copy code
fun x(a: String = "") {
println(this::x.parameters.first().name)
}
x()
// prints: a
Erik
01/30/2020, 7:39 AM
I.e. a reference to the function and then get its parameters, but then you must know the parameter's index (or just take the first like I did here)
Erik
01/30/2020, 7:40 AM
Ah, I see you've edited your question and my answer is probably not what you're looking for
a
aeruhxi
01/30/2020, 7:41 AM
Yeah, I guess there is no way, right?
e
Erik
01/30/2020, 7:44 AM
I guess not.
Erik
01/30/2020, 7:46 AM
It seems to me that if you need the name of something from outside of the function's scope, then you should pass that name in as a parameter. It's the outside scope that knows this name, after all. If there even is a name.
Erik
01/30/2020, 7:47 AM
Because
Copy code
val name = ""
x(name)
and
Copy code
x("")
behave the same, but in your case you probably want different behaviour in