我想在 Kotlin 中改进此代码,似乎太多余了
.forEach和Lambda可以实现,但是我不知道如何 有人可以帮忙吗?
val Point1 : List<Double> = topleft
.split(",")
.map {
it
.trim()
.toDouble()
}
val Point2 : List<Double> = topright
.split(",")
.map {
it
.trim()
.toDouble()
}
val Point3 : List<Double> = bottomright
.split(",")
.map {
it
.trim()
.toDouble()
}
val Point4 : List<Double> = bottomleft
.split(",")
.map {
it
.trim()
.toDouble()
}
最后,我想 拥有所有这些值的一个列表 。
topleft,topright ...是类似 42.1234,54.23423
的字符串
(地理坐标)
答案 0 :(得分:6)
您应该创建一个可以对每个列表重复的功能。像这样:
fun String.splitToDoubles() = split(",").map { it.trim().toDouble() }
val point1 = topleft.splitToDoubles()
val point2 = topright.splitToDoubles()
val point3 = bottomright.splitToDoubles()
val point4 = bottomleft.splitToDoubles()
请注意,科特林的约定是val
和var
以小写字母(point1
而不是Point1
)开头。