Assuming I have such method: ```fun foo(name: Stri...
# getting-started
i
Assuming I have such method:
Copy code
fun foo(name: String = "noname") {
   //...
}
How can I retrieve the default value (
noname
) via reflection?
e
you can't
it could be
fun foo(name: String = any.complex.expression())
, which is not retained in source form anywhere and not something the reflection api can represent
✔️ 1
a
something like what you’re asking might be possible with Kapshot https://github.com/mfwgenerics/kapshot, which I think uses KSP under the hood
e
it doesn't use KSP. expressions aren't available to annotation processors either
a
ahh okay, thanks
g
Interesting question: how are these default values treated by the compiler? Does the compiler insert the default value on the caller’s side to complete the call or does the compiler create overloaded functions? If the compiler does the first thing, it is likely that nothing will remain in the compiled files.
e
neither, the default values are implemented in the callee (which is the only way it could work as they are allowed access to private etc.)
e.g. that desugars to something like
Copy code
public void foo(String name, int bits) {
    if ((bits & 1) == 0) name = "noname"
and Kotlin callers invoke
foo("somename", 1)
or
foo(null, 0)
well it actually goes into a separate synthetic function but same idea
g
Very interesting, thank you. That means, such a function is callable from Java, but you have to supply every parameter.
e
there is
@JvmOverloads
to instruct the compiler to generate more overloads so that Java can call without supplying every parameter, but it only works for dropping parameters at the end
e.g.
Copy code
@JvmOverloads fun foo(x: Int = 0, y: Int = 0)
Kotlin callers can call
foo(x = 1)
and
foo(y = 1)
, but Java callers don't have an overload for the latter (how?)
🙏 1