Kotlin用Collection中的lastOrNull()替换isEmpty()和last()

mtr*_*kal 3 collections list arraylist kotlin

我想使用类似的代码(下面的代码),但我认为必须有一个更好的解决方案,lastOrNull()而不是使用isEmptylast()

data class Entry(val x: Float, val y: Float)
Run Code Online (Sandbox Code Playgroud)
var entries: MutableList<Entry> = ArrayList()
if(some) {
  entries.add(Entry(100f, 200f)
}
val foo = (if (entries.isEmpty()) 0f else entries.last().y) + 100f
Run Code Online (Sandbox Code Playgroud)

还有更好的方法entries.lastOrNull()?.y if null 0f吗?

hol*_*ava 6

你可以使用Kotlin elvis操作符 ?:,例如:

//   if the expression `entries.lastOrNull()?.y` is null then return `0f` 
//                                  v              
val lastY = entries.lastOrNull()?.y ?: 0f
Run Code Online (Sandbox Code Playgroud)

对于上面代码中的表达式,您可以使用safe-call ?.let/?.run使代码更清晰,例如:

//val foo = if (entries.isEmpty()) 0f else entries.last().y + 100f else 100f

//             if no Entry in List return `0F`  ---v
val foo = entries.lastOrNull()?.run { y + 100 } ?: 0F 
//                            ^--- otherwise make the last.y + 100  
Run Code Online (Sandbox Code Playgroud)