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
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)