Preface
Those who have used C# may not be able to put down the yield keyword, so people like me who are forced to board the java pirate ship want to find similar functions.
For the yield keyword in C#, you can refer to this article:https:///article/
I'm using kotlin, and the following method demonstrates the function of generating a sequence.
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>){ (50).forEach { println(it) } }
The program will be executed 50 times and then exit.
Implement the enumerator
The above code uses sequence function, not a common enumerator. The following code is more like the C# enumerator.
class MyList : Iterable<Int>{ private val list = arrayOf(1,2,3,4,5,6) override fun iterator(): Iterator<Int> { return buildIterator { val 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) } }
Implement similar to Linq
When we use Linq, we can continuously transform sequences, and Kotlin can also be easily processed.
//The input data + 1fun Do1(seq : Sequence<Int>) : Sequence<Int>{ return buildSequence { for (i in seq){ yield(i + 1) } } } //Convert to stringfun Do2(seq : Sequence<Int>) : Sequence<String>{ return buildSequence { for (i in seq){ yield("hello $i ") } } } //Aggregate multiple data into one datafun 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(()))) for (p in result){ println(p) } }
Summarize
The above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.