Is it possible to assign a parameter of a composab...
# compose
p
Is it possible to assign a parameter of a composable only if that parameter is different from a value? for example, having a Text, assign the font size received on a variable only if it is different from 0
k
We can also achieve this as well by using the condition. For Example, you can provide a parameter inside the composable. and you can write a condition like if font==0 and do that or you can also use the takeIf operator as well. here is the example code:
Copy code
@Composable
fun ConditionalText(
    text: String,
    fontSize: Int
) {
    Text(
        text = text,
        fontSize = fontSize.takeIf { it != 0 }?.sp ?: 16.sp
    )
}

Or 

You can use this one as well:
fontSize = if (fontSize != 0) fontSize.sp else 16.sp
p
but in that case I need to force an else
is it possible to assign the parameter only if the condition is true?
my interest is to leave the parameters untouched if the condition is not reach
z
The only way to do that is to make a separate call to
Text
, eg
Copy code
if (fontSize != 0) {
  Text(text = text, fontSize = fontSize.sp)
} else {
  Text(text = text)
}
p
ouch, ok, and what if I pass the default value in the else to avoid making separate calls?
I checked the Text function, and the default value it uses is "TextUnit.Unspecified" for textsize, and "Color.Unspecified" for text color. If I pass those values as the third option when the color and the size are not being parametrized (null or invalid value) is OK?
Copy code
Text(
    text = text,
    color = intColor?.let { Color(intColor) } ?: Color.Unspecified,
    fontSize = spTextSize ?: oldTextSize ?: TextUnit.Unspecified,
    modifier = modifier
)
z
I would go with that approach. The text defaults are unlikely to change from
Unspecified
, and even if they did the function would still need to handle those values, so it’s pretty safe
p
so Unspecified means that the default OS color or text size will be used?
for example, in TextUnit.Unspecified I can read this:
Copy code
A special TextUnit instance for representing inheriting from parent value.
Notice that performing arithmetic operations on Unspecified may result in an IllegalArgumentException.
I can't see where that is explaining that the default size will be used
maybe because "inheriting from parent value" means that will get the size of the theme for that kind of composable?
e
across the Compose types, Unspecified is generally treated as the "null" value (without needing to use
null
which would force boxing for primitive/value types)
240 Views