I have pairs value and want to use in vararg
. The value is something like this answer
val verticalBrush2 = Brush.verticalGradient(
0.25f to Color.Blue,
1f to Color.Red,
)
I have some business logic to use different colors. So I converted into like this
val brushColors = listOf(0.25f to Color.Blue, 1f to Color.Red)
Now I passed in drawLine
brush parameter which is type of vararg
. I followed this answer to convert into toTypedArray()
.
drawLine(
brush = Brush.verticalGradient(
listOf(0.25f to Color.Blue, 1f to Color.Red)
.map { it }
.toTypedArray()
),
start = Offset(x = 0F, y = 0F),
end = Offset(x = 0F, y = size.height),
strokeWidth = 3.dp.toPx(),
)
But still gives me error
>Solution :
You missed the spread operator. From Kotlin docs:
When you call a vararg-function, you can pass arguments individually, for example asList(1, 2, 3). If you already have an array and want to pass its contents to the function, use the spread operator (prefix the array with *):
So you have to convert your list to array and use the spread operator:
Brush.verticalGradient(*brushColors.toTypedArray())
You don’t need .map { it }
, it doesn’t do anything.