For e.g. how can I add +1 to each element of a list using foreach
Edit:
To answer your updated question, you can definitely use foreach
:
alist.foreach(x => println(x + 1))
You can't use placeholder syntax inside println
since the compler infers it as:
alist.foreach(x => println(x => x + 1))
According to it's expansion laws. println
takes a parameter of type Any
, so it can't bind it to a concrete type with a plus method.
If you're interested in the rules of placeholder syntax, see Hidden features of Scala
You cannot mutate a List[+A]
using foreach
in Scala, since lists are immutable and foreach
return type is Unit
. What you can do is project a new list from an existing one using the map
transformation:
scala> val list = List(1,2,3,4)
list: List[Int] = List(1, 2, 3, 4)
scala> val plusOneList = list.map(_ + 1)
plusOneList: List[Int] = List(2, 3, 4, 5)
If you look at the signature for foreach
, you see that it takes a function: A => Unit
, which takes an element of type A and projects back a Unit. This signature is a sign for a side effecting method and since list is immutable, that doesn't help us.
If you used a mutable list, such as ListBuffer
, then you could use side effects for population:
scala> val listBuffer = mutable.ListBuffer[Int]()
listBuffer: scala.collection.mutable.ListBuffer[Int] = ListBuffer()
scala> (0 to 4).foreach(x => listBuffer += x)
scala> listBuffer
res10: scala.collection.mutable.ListBuffer[Int] = ListBuffer(0, 1, 2, 3, 4)