英文:
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:
val brushArray = brushStopColors.map { it.color.toString() }
And want to change brushArray
to .toTypedArray()
and pass it into a different function. It looks like this:
fun verticalGradient(vararg colorStops: Pair<Float, String>) {
// more code here
}
When I pass the array, it's giving me an error:
val brushArray = brushStopColors.map { it.color.toString() }.toTypedArray()
verticalGradient(*brushArray)
Error:
Type mismatch.
Required:
Array<out Pair<Float, String>>
Found:
Array
Image:
英文:
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
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
答案1
得分: 1
The above returns a list of String instead of a list of Pair.
请使用以下代码:
fun BrushStopColors.toPair(): Pair<Float, String> = Pair(this.stopPoint, this.color.toString())
val brushArray = brushStopColors.map { it.toPair() }.toTypedArray()
或者更加简洁:
val brushArray = brushStopColors.map { Pair(it.stopPoint, it.color.toString()) }.toTypedArray()
英文:
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()
答案2
得分: 1
如果您打印brushArray,您将看到它将整个对象映射到一个字符串。我会使用这样的扩展函数:
fun BrushStopColors.toGradientPair() = Pair<Float, String>(this.stopPoint, this.color.toString())
英文:
If you print the brushArray you'll see that it maps the entire object to a String. I would use an extension function like this:
fun BrushStopColors.toGradientPair() = Pair<Float, String>(this.stopPoint, this.color.toString())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论