What is Scala's yield?

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

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

9条回答
  •  时光说笑
    2020-11-22 11:31

    Consider the following for-comprehension

    val A = for (i <- Int.MinValue to Int.MaxValue; if i > 3) yield i
    

    It may be helpful to read it out loud as follows

    "For each integer i, if it is greater than 3, then yield (produce) i and add it to the list A."

    In terms of mathematical set-builder notation, the above for-comprehension is analogous to

    set-notation

    which may be read as

    "For each integer i, if it is greater than 3, then it is a member of the set A."

    or alternatively as

    "A is the set of all integers i, such that each i is greater than 3."

提交回复
热议问题