How to perform an operation in scala's foreach?

前端 未结 4 1815
时光取名叫无心
时光取名叫无心 2021-01-21 03:33

I am trying to understand how to perform an operation when using foreach. For e.g. how can I print element+1 of alist using foreach

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-21 04:04

    The issue here is that Scala thinks you're trying to pass a function "(something)+1" to the println method rather than passing it to the foreach method.

    Doing just "println(_)" works because in this case you're not passing a function to println. Instead you're defining a partial application of println. The partial application is a function and can be passed to foreach.

    This will work for you:

    alist.map(_+1).foreach(println)
    

提交回复
热议问题