用過c#的可能對 yield 關鍵字愛不釋手,那麼在像我這種被迫上java賊船的人,就想找到相似的功能。java
我使用的是kotlin,下面的方法演示了產生一個序列的功能。c#
val fibonacciSeq = buildSequence { var a = 0 var b = 1 yield(1) while (true) { yield(a + b) val tmp = a + b a = b b = tmp } } fun main(args: Array<String>){ fibonacciSeq.take(50).forEach { println(it) } }
程序將執行50次而後退出。ide
上面的代碼使用的是序列功能,並不是是常見的枚舉器,下面的代碼更像c#的枚舉器。ui
class MyList : Iterable<Int>{ private val list = arrayOf(1,2,3,4,5,6) override fun iterator(): Iterator<Int> { return buildIterator { val size = list.size for(i in 0 until size) { yield(list[i] + i) } } } } fun main(args: Array<String>){ val list = MyList() for (p in list) { println(p) } }
咱們在使用Linq時能夠將序列不斷的變換,Kotlin也能夠很方便的處理。spa
//將輸入的數據 + 1 fun Do1(seq : Sequence<Int>) : Sequence<Int>{ return buildSequence { for (i in seq){ yield(i + 1) } } } //變換成字符串 fun Do2(seq : Sequence<Int>) : Sequence<String>{ return buildSequence { for (i in seq){ yield("hello $i ") } } } //將多個數據聚合到一個數據 fun Do3(seq : Sequence<String>) : Sequence<String>{ return buildSequence{ var result = "" var count = 0 for (i in seq){ result += i count++ if(count == 3){ yield(result) result = "" count = 0 } } if(count > 0){ yield(result) } } } fun main(args: Array<String>){ val data = arrayOf(1,2,3,4,5,6,7,8) val result = Do3(Do2(Do1(data.asSequence()))) for (p in result){ println(p) } }