科特林平面图解压缩数据类列表

问题描述 投票:2回答:2

给出二维坐标列表是数据类

data class Point(val x: Int, val y:Int)
val points: List<Point>

和一个TornadoFX(Kotlin中的JavaFX)方法,它采用[x,y,x2,y2 ...]的扁平数组:

polyline(vararg points: kotlin.Number)

我只是写了以下内容,然后离开了,感觉这不可能全部都有

fun List<Point>.asPolyline() = this.flatMap { p -> listOf(p.component1(), p.component2()) }

polyline(*points.asPolyline().toTypedArray())

没有办法扩展数据类(类似于Array*的扩展方式,还是简单的更好的转换方式?

kotlin flatten tornadofx
2个回答
0
投票

我找不到一种完全不同的方式来执行此操作,但是我认为如果我们使用foldMutableList,则可以在不为每个List分配Point的情况下完成此操作:

fun List<Point>.asPolyline(): List<Number> = this.fold(mutableListOf()) { next, carry -> 
    next.apply {
        this.add(carry.x)
        this.add(carry.y)
    }
}

0
投票

这是一种使用最少分配的方法:

fun List<Point>.toFlatArray() = 
    Array(size * 2) { with (this[it / 2]) { if (it % 2 == 0) x else y } }
© www.soinside.com 2019 - 2024. All rights reserved.