What is Scala's yield?

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

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

9条回答
  •  庸人自扰
    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.

提交回复
热议问题