https://kotlinlang.org logo
Title
a

Ansh Tyagi

02/05/2022, 12:45 PM
Not sure what the right channel would be to ask this, but is there a hack to get a map of the named params of a function to their value. For example:
fun xyz(param1,param2,param3...)
and get something like
{"param1":param1, "param2": param2 … }
its very laborious and redundant to do mapOf. Any workarounds?
j

Joffrey

02/05/2022, 12:51 PM
What's your use case for this? Looks like a potential XY problem
☝️ 1
a

Ansh Tyagi

02/05/2022, 12:57 PM
So i wanna map these named param to values to log it as the api request body.
j

Javier

02/05/2022, 4:02 PM
@Big Chungus has a json dsl lib
I am on mobile but maybe he can share it here
a

Ansh Tyagi

02/05/2022, 4:43 PM
@Javier i dont really think its a JSON problem. I need some workaround to get function parameters to map like -> NameOfTheParam to ValueOfTheParam. but happy to look if the library has some apis to do so
the only workaround i think of right now is to use reflection
but this^ wont help in getting the value of the param
m

Mykola Gurov

02/06/2022, 4:11 PM
One option is to extract the parameters into a data class, so that instead of
fun xyz(param1, param2, param3
you’d call
fun xyz(XyzParams(param1="value1", param2="value2", param3="value3"))
etc. The Pro of this approach is that it’s usually a good practice to introduce such params for functions with lengthy signatures anyways. The Con is that this might be tedious and repetitive on itself.