What is Scala's yield?

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

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

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

    Yes, as Earwicker said, it's pretty much the equivalent to LINQ's select and has very little to do with Ruby's and Python's yield. Basically, where in C# you would write

    from ... select ??? 
    

    in Scala you have instead

    for ... yield ???
    

    It's also important to understand that for-comprehensions don't just work with sequences, but with any type which defines certain methods, just like LINQ:

    • If your type defines just map, it allows for-expressions consisting of a single generator.
    • If it defines flatMap as well as map, it allows for-expressions consisting of several generators.
    • If it defines foreach, it allows for-loops without yield (both with single and multiple generators).
    • If it defines filter, it allows for-filter expressions starting with an if in the for expression.

提交回复
热议问题