Apply a callback to an array: Difference between revisions

(→‎{{header|FP}}: Changed compiler link to internal link)
Line 556:
=={{header|Scala}}==
val l = List(1,2,3,4)
l.foreach {i => Console.println(i)}
 
When the argument appears only once -as here, i appears only one in println(i) - it may be shortened to
l.foreach(println(_))
Same for an array
val a = Array(1,2,3,4)
a.foreach {i => Console.println(i)}
a.foreach(println(_)) '' // same as previous line''
 
// Or for an externally defined function :
def doSomething(in: int) = {Console.println("Doing something with "+in)}
l.foreach(doSomething)
 
There is also a ''for'' syntax, which is internally rewritten to call foreach. A foreach method must be define on ''a''
for(val i <- a) Console.println(i)
 
It is also possible to apply a function on each item of an list to get a new list (same on array and most collections)
val squares = l.map{i => i * i} ''//returnssquares is'' List(1,4,9,16)
 
Or the equivalent ''for'' syntax, with the additional keyword ''yield'', map is called instead of foreach
Anonymous user