官术网_书友最值得收藏!

Building sequences

As I mentioned earlier, Kotlin coroutines are something more than threads in Java and async/await in C#. Here is a feature that, after learning, you will be pissed that it was not there while you were learning to code. To add icing on the cake, this feature is application level, it is even shipped with kotlin-stdlib, so you can use it right there without doing anything or even using coroutines explicitly.

Before learning what I am talking about, let's do some old school code, say the fibonacci series? Consider the following piece of code as an example:

    fun main(args: Array<String>) { 
      var a = 0 
      var b = 1 
      print("$a, ") 
      print("$b, ") 
 
      for(i in 2..9) { 
        val c = a+b 
        print("$c, ") 
        a=b 
        b=c 
      } 
    } 

So, this is the old-school fibonacci series program in Kotlin. This code becomes more problematic when you plan to take the user input for how many numbers to print. What if I say Kotlin has a buildSequence function that can do this task for you, that too pretty naturally and in a simpler way? So, let's modify the code now:

    fun main(args: Array<String>) { 
      val fibonacciSeries = buildSequence {//(1) 
        var a = 0 
        var b = 1 
        yield(a)//(2) 
        yield(b) 
 
        while (true) { 
            val c = a+b 
            yield(c)//(3) 
            a=b 
            b=c 
        } 
     } 
 
     println(fibonacciSeries.take(10) join "," )//(4) 
 
    } 

The following is the output for both the programs:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 

Now, let's understand the program. On comment (1), we declare val fibonacciSeries to be filled up by the buildSequence block. Whenever we have computed some value to output to the sequence/series, we will yield that value (in comment 2 and 3). On comment 4, we call fibonacciSeries to compute up to the 10th variable and join elements of the sequence with a comma (,).

So, you learned coroutine; now, let's implement it into our program.

主站蜘蛛池模板: 资中县| 营口市| 肥乡县| 西昌市| 巧家县| 沙河市| 美姑县| 濮阳县| 南陵县| 上犹县| 舞钢市| 樟树市| 南开区| 墨脱县| 南通市| 新巴尔虎左旗| 江津市| 舟山市| 昌吉市| 崇阳县| 包头市| 清涧县| 汕尾市| 河曲县| 沅陵县| 原平市| 绵阳市| 广德县| 车险| 玉树县| 常熟市| 连云港市| 陆河县| 泌阳县| 新津县| 印江| 姜堰市| 辉县市| 聂拉木县| 麦盖提县| 涿鹿县|