https://kotlinlang.org logo
#reflect
Title
# reflect
j

juancho

11/17/2018, 6:54 PM
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

Eugenio

11/17/2018, 7:43 PM
Sadly... You can't! That expression is just like a method body: compiled code
j

juancho

11/17/2018, 8:11 PM
oh it’s true! 😞 thanks man!
Did you got any workaround for this?
e

Eugenio

11/17/2018, 8:33 PM
Hmmm not really, but it depends on the use case. What are you trying to do?
j

juancho

11/17/2018, 8:41 PM
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

Eugenio

11/17/2018, 8:43 PM
Are you generating Kotlin or Java?
j

juancho

11/17/2018, 8:44 PM
Kotlin (Kotlin Poet)
e

Eugenio

11/17/2018, 8:46 PM
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

juancho

11/17/2018, 8:49 PM
yes looks like this is the only option
Thanks man! really appreciated your help on this and super fast response 🙇‍♂️
e

Eugenio

11/17/2018, 8:50 PM
No problem! Hope you can make it work ;)
j

juancho

11/17/2018, 8:50 PM
thanks man!!