What is Scala's yield?

前端 未结 9 763
忘掉有多难
忘掉有多难 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.
    0 讨论(0)
  • 2020-11-22 11:36

    yield is more flexible than map(), see example below

    val aList = List( 1,2,3,4,5 )
    
    val res3 = for ( al <- aList if al > 3 ) yield al + 1 
    val res4 = aList.map( _+ 1 > 3 ) 
    
    println( res3 )
    println( res4 )
    

    yield will print result like: List(5, 6), which is good

    while map() will return result like: List(false, false, true, true, true), which probably is not what you intend.

    0 讨论(0)
  • 2020-11-22 11:42
    val aList = List( 1,2,3,4,5 )
    
    val res3 = for ( al <- aList if al > 3 ) yield al + 1
    val res4 = aList.filter(_ > 3).map(_ + 1)
    
    println( res3 )
    println( res4 )
    

    These two pieces of code are equivalent.

    val res3 = for (al <- aList) yield al + 1 > 3
    val res4 = aList.map( _+ 1 > 3 )
    
    println( res3 ) 
    println( res4 )
    

    These two pieces of code are also equivalent.

    Map is as flexible as yield and vice-versa.

    0 讨论(0)
提交回复
热议问题