Kotlin的新手-好奇是否有更优雅的方式为以下类(或任何其他样式技巧或陷阱)编写duration
getter:
open class Timeline(
open var props: MutableList<Prop> = mutableListOf()) {
val duration: Long
get() {
var best: Prop? = null
props.forEach {
if (best == null || it.interval.end > best?.interval!!.end) {
best = it
}
}
return best?.interval?.end ?: 0L
}
}
从本质上讲,它只是在寻找间隔最大的道具。我知道,我可以确保在向其中添加项目时对props
List
进行排序,并且只需在列表末尾抓取该项目即可,但这不是问题。
答案 0 :(得分:3)
如果您尝试找到end
的最大值,则可以单行执行:
val duration: Long =
props.map { it.interval.end }.max() ?: 0L
基本上是这样说的:“将每个Prop
转换为其interval.end
的值并取最大值。如果没有最大值,则返回0。”
要对此进行扩展,如果您想要具有最高Prop
的{{1}},则可以这样写:
interval.end
其含义是:“用最大的val bestProp: Prop? =
props.maxBy { it.interval.end }
查找Prop
,如果找不到,则为null”。