您可以将val sequence = sequence {
val start = 0
// yielding a single value
yield(start)
// yielding an iterable
yieldAll(1..5 step 2)
// yielding an infinite sequence
yieldAll(generateSequence(8) { it * 3 })
}
println(sequence.take(7).toList()) // [0, 1, 3, 5, 8, 24, 72]
视为“返回,下一次从您停止的位置开始:”]]
yield()
它创建状态机和内容,但是您可以将其转换为类似Java的内容:
val sequence = sequence { val start = 0 yield(start) // first return yieldAll(1..5 step 2) // if called again, will start from here yieldAll(generateSequence(8) { it * 3 }) // if called more that six times, start from here }
在Java类中,我们通过具有两个变量:
class Seq { private AtomicInteger count = new AtomicInteger(0); private int state = 0; public int nextValue() { if (count.get() == 0) { return state; } else if (count.get() >= 1 && count.get() <= 5) { state += 2; return state; } else { state *= 3; return state; } } }
和count
来维护显式状态。state
和sequence
的组合允许隐式维护此状态。
让我们考虑一个示例,您可以在其中生成序列的下一个元素,但是看不到实现Java迭代器的简便方法。