3. Higher order functions
Short summary of first class functions:
val even: (Int => Boolean) = (i: Int) => i % 2 == 0
Same type definition:
def test(numbers: List[Int], f: Int => Boolean) = ...
Call:
test(List(1, 2, 3), (i: Int) => i % 2 == 0)
4. Higher order functions
def test(numbers: List[Int], f: Int => Boolean) =
numbers.map(tall => f(tall))
// List[Boolean]
5. Higher order functions
Functions with several parameters must list them
in parenthesis:
def test(l: List[String], f: (Int, String) => Boolean)
6. call-by-value vs. call-by-name
by-value: expressions are evaluated before being
passed to the function
by-name: expressions evaluated inside function
nice when computationally expensive
possible to create nice APIs
11. def using[T <: { def close() }, A]
(closeable: T)
(f: T => A) = {
try {
f(closeable)
} finally {
if (closeable != null) {
try {
closeable.close()
}
catch {
case e: Exception => // Do something clever!?
}
}
}
}
12. Tasks (30 min)
Open 'higher-order-functions' project
Tests in scalaexamples.higherorderfunctions
Add @Test to one and one method
Implement missing functions in PersonFilter and
so on.
Follow instructions in code
Make tests pass