给出二维坐标列表是数据类
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
和*
的扩展方式,还是简单的更好的转换方式?
我找不到一种完全不同的方式来执行此操作,但是我认为如果我们使用fold
和MutableList
,则可以在不为每个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 } }