Hi everyone. Let me ask a weird question to grab y...
# compose-android
n
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
Easiest way is `if`/`else` at the call site
n
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
I'm saying
Copy code
val thing = if (yourThing != null) {
  CreateTheThing(thing = yourThing)
} else {
  CreateTheThing()
}
n
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
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
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
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
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 ๐Ÿค”