Hi everyone! Does anyone know how to get the “defa...
# reflect
j
Hi everyone! Does anyone know how to get the “default value” from a constructor parameter using annotation processor and kotlin-metadata? Example:
class Foo(val bar: Int = 1)
how do I get the value
1
?
e
Sadly... You can't! That expression is just like a method body: compiled code
j
oh it’s true! 😞 thanks man!
Did you got any workaround for this?
e
Hmmm not really, but it depends on the use case. What are you trying to do?
j
I’m creating a builder class of the annotated class:
Copy code
@MyAnnotation
class Foo(val bar: Int = 1)
At the moment to create the Foo class from the generated Builder I would like to pass
bar
if it was set in the builder or just invoke
Foo()
if it was not set. But the problem is that the constructor can have a mix of params with and without default params
e
Are you generating Kotlin or Java?
j
Kotlin (Kotlin Poet)
e
Ok, so, you can know which parameters have defaults and their names, so once you have all required params you can generate all combinations of calling the constructor with the optional params absent
It's not pretty, but it might be the only way
j
yes looks like this is the only option
Thanks man! really appreciated your help on this and super fast response 🙇‍♂️
e
No problem! Hope you can make it work ;)
j
thanks man!!