Kotlin 平面图解压数据列表 class

Kotlin flatmap to unpack List of data class

给定一个二维坐标列表这是一个数据class

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

有没有办法扩展数据 class(类似于 Array* 的传播方式)或只是进行此转换的更好方法?

我找不到完全不同的方法来做到这一点,但我认为如果我们使用 foldMutableList,则无需 List 分配即可完成对于每个 Point:

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

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

fun List<Point>.toFlatArray() = 
    Array(size * 2) { with (this[it / 2]) { if (it % 2 == 0) x else y } }