Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use list value in vararg in kotlin

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().

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

                    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

enter image description here

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading