Anonymous user
Apply a callback to an array: Difference between revisions
→{{header|Scala}}
(→{{header|FP}}: Changed compiler link to internal link) |
|||
Line 556:
=={{header|Scala}}==
val l = List(1,2,3,4)
l.foreach {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 =>
a.foreach(println(_)) '' // same as previous line''
def doSomething(in: int) = {
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)
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} ''//
Or the equivalent ''for'' syntax, with the additional keyword ''yield'', map is called instead of foreach
|