Expansion of Function Values
An anonymous function such as
(x: Int) => x * x
is expanded to:
class AnonFun extends Function1[Int, Int] {
def apply(x: Int) = x * x
}
new AnonFun
or, shorter, using anonymous class syntax:
new Function1[Int, Int] {
def apply(x: Int) = x * x
}
Expansion of Function Calls
A function call, such as f(a, b), where f is a value of some class type, is expanded to:
f.apply(a, b)
So the OO-translation of:
val f = (x: Int) => x * x
f(7)
would be:
val f = new Function1[Int, Int] {
def apply(x: Int) = x * x
}
f.apply(7)
map
Thus, instead of writing the following:
xs.map(x => x + 1)
You can write:
for (x <- xs) yield x + 1
You can read it as “for every value, that I name ‘x’, in ‘xs’, return ‘x + 1’”.
filter
Also, instead of writing the following:
xs.filter(x => x % 2 == 0)
You can write:
for (x <- xs if x % 2 == 0) yield x
The benefit of this syntax becomes more apparent when it is combined with the previous one:
for (x <- xs if x % 2 == 0) yield x + 1
Equivalent to the following:
xs.filter(x => x % 2 == 0).map(x => x + 1)
flatMap
Finally, instead of writing the following:
xs.flatMap(x => ys.map(y => (x, y)))
You can write:
for (x <- xs; y <- ys) yield (x, y)
You can read it as “for every value ‘x’ in ‘xs’, and then for every value ‘y’ in ‘ys’, return ‘(x, y)’”.