https://kotlinlang.org logo
#getting-started
Title
# getting-started
i

igor.wojda

02/22/2023, 1:30 PM
Assuming I have such method:
Copy code
fun foo(name: String = "noname") {
   //...
}
How can I retrieve the default value (
noname
) via reflection?
e

ephemient

02/22/2023, 1:32 PM
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

Adam S

02/22/2023, 1:47 PM
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

ephemient

02/22/2023, 1:48 PM
it doesn't use KSP. expressions aren't available to annotation processors either
a

Adam S

02/22/2023, 1:49 PM
ahh okay, thanks
g

Goetz Markgraf

02/22/2023, 1:54 PM
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

ephemient

02/22/2023, 1:55 PM
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

Goetz Markgraf

02/22/2023, 2:01 PM
Very interesting, thank you. That means, such a function is callable from Java, but you have to supply every parameter.
e

ephemient

02/22/2023, 2:04 PM
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
4 Views