What is Scala's yield?

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

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

9条回答
  •  醉话见心
    2020-11-22 11:29

    Unless you get a better answer from a Scala user (which I'm not), here's my understanding.

    It only appears as part of an expression beginning with for, which states how to generate a new list from an existing list.

    Something like:

    var doubled = for (n <- original) yield n * 2
    

    So there's one output item for each input (although I believe there's a way of dropping duplicates).

    This is quite different from the "imperative continuations" enabled by yield in other languages, where it provides a way to generate a list of any length, from some imperative code with almost any structure.

    (If you're familiar with C#, it's closer to LINQ's select operator than it is to yield return).

提交回复
热议问题