What is Scala's yield?

前端 未结 9 834
忘掉有多难
忘掉有多难 2020-11-22 11:06

I understand Ruby and Python\'s yield. What does Scala\'s yield do?

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 11:26

    Yield is similar to for loop which has a buffer that we cannot see and for each increment, it keeps adding next item to the buffer. When the for loop finishes running, it would return the collection of all the yielded values. Yield can be used as simple arithmetic operators or even in combination with arrays. Here are two simple examples for your better understanding

    scala>for (i <- 1 to 5) yield i * 3
    

    res: scala.collection.immutable.IndexedSeq[Int] = Vector(3, 6, 9, 12, 15)

    scala> val nums = Seq(1,2,3)
    nums: Seq[Int] = List(1, 2, 3)
    
    scala> val letters = Seq('a', 'b', 'c')
    letters: Seq[Char] = List(a, b, c)
    
    scala> val res = for {
         |     n <- nums
         |     c <- letters
         | } yield (n, c)
    

    res: Seq[(Int, Char)] = List((1,a), (1,b), (1,c), (2,a), (2,b), (2,c), (3,a), (3,b), (3,c))

    Hope this helps!!

提交回复
热议问题