我有一个Grid类,它是二维Cell对象数组的包装器。我希望这个类实现Iterable<Cell>接口,以便在循环中使用它并直接迭代整个单元格。有没有一种简单的方法可以做到这一点?Kotlin 是否支持yield return样式迭代器?我目前的解决方案非常冗长:
override fun iterator() = object : Iterator<Cell> {
val currentOuter = grid.iterator() // grid is object of Array<Array<Cell>>
var currentInner = if (currentOuter.hasNext()) currentOuter.next().iterator() else arrayOf<Cell>().iterator()
override fun next(): Cell {
if (!hasNext()) {
throw NoSuchElementException()
}
return if (currentInner.hasNext()) {
currentInner.next()
} else {
currentInner = currentOuter.next().iterator()
currentInner.next()
}
}
override fun hasNext(): Boolean {
return currentInner.hasNext() || currentOuter.hasNext()
}
}
Run Code Online (Sandbox Code Playgroud) 你知道是否有一个快捷方式:
if (x == null) null else f(x)
Run Code Online (Sandbox Code Playgroud)
对于Java, Optional您可以这样做:
x.map(SomeClass::f)
Run Code Online (Sandbox Code Playgroud)