What is Scala's yield?

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

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

9条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题