https://kotlinlang.org logo
#compose-android
Title
# compose-android
n

nglauber

09/29/2023, 1:51 PM
Hi everyone. Let me ask a weird question to grab your attention 🙂 "Is there a way to call a function and pass the optional parameter conditionally?" Practical example: I need to create an instance of
TopAppBarColors
. The constructor of this class and its fields are
private
. The only way to create a
TopAppBarColors
is via
TopAppBarDefaults.topAppBarColors
function which all parameters are optional. So, I just would like to pass the parameter if the value I have is not null.
j

jw

09/29/2023, 1:53 PM
Easiest way is `if`/`else` at the call site
n

nglauber

09/29/2023, 1:54 PM
That's the problem... I don't have the right default value 😕
Like, if I grab the value from the
TopAppBarDefaults.topAppBarColors
they are all private/internal 😞
j

jw

09/29/2023, 1:54 PM
I'm saying
Copy code
val thing = if (yourThing != null) {
  CreateTheThing(thing = yourThing)
} else {
  CreateTheThing()
}
n

nglauber

09/29/2023, 1:55 PM
But in this case, I have a combination of 5 values
Copy code
if a != null
  CreateThing(a)
else if a != null && b != null
  CreateThing(a, b)
else if a != null && b != null && c != null
  CreateThing(a, b, c)
...
if would be 32 if/elseif 😕
j

jw

09/29/2023, 2:00 PM
The underlying invocation mechanism supports this, but it's not surfaced in the language. So the two possible ways to do it today (other than 2^N if/elses) are via reflection or writing a compiler plugin. Neither feel like great solutions.
😞 1
n

nglauber

09/29/2023, 2:03 PM
Thanks @jw. I think I'm going to use reflection for now... I mean, I will create a default
TopAppBarColors
and get the values from this instance via reflection...
and add a
FIXME
for future reference 😄
j

jw

09/29/2023, 2:04 PM
Yeah that works. The other reflection way is to assemble the
Int
whose bits represent whether an argument value was passed by the caller or whether they're relying on the default. There's a synthetic method overload which accepts all arguments, plus the bit-packed int, plus a marker object that you could then call.
n

nglauber

09/29/2023, 2:07 PM
I will have to do this in a few classes. Not only for TabAppBarColors... So maybe I should stick with the simpler (and maybe less efficient) solution 🤔
2 Views