有没有更优雅的方式在Kotlin中编写此吸气剂?

时间:2019-03-30 18:26:26

标签: kotlin

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进行排序,并且只需在列表末尾抓取该项目即可,但这不是问题。

1 个答案:

答案 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”。