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

Convert data class value into different in kotlin

I have a data class like this

data class BrushStopColors(
    val stopPoint: Float,
    val color: Int,
)

I have a list

val brushStopColors = listOf(
        BrushStopColors(0.3F, 1),
        BrushStopColors(1F, 1),
    )

I want to convert my color from Int to String or any other format. So I tried this code

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

val brushArray = brushStopColors.map { it.color.toString() }

And want to change brushArray to .toTypedArray() and passing into different function. It looks like this

fun verticalGradient(vararg colorStops: Pair<Float, String>){
   /// more code in here
}

When I passed the array it’s giving me error

val brushArray = brushStopColors.map { it.color.toString() }.toTypedArray()
verticalGradient(*brushArray)

Error

Type mismatch.
Required:
Array<out Pair<Float, String>>
Found:
Array<String>

Image

enter image description here

>Solution :

val brushArray = brushStopColors.map { it.color.toString() }

The above returns a list of String instead of a list of Pair.

Please use this:

fun BrushStopColors.toPair(): Pair<Float, String> = Pair(this.stopPoint, this.color.toString())


val brushArray = brushStopColors.map { it.toPair() }.toTypedArray()

Or even more concise :

val brushArray = brushStopColors.map { Pair(it.stopPoint, it.color.toString()) }.toTypedArray()
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