This document discusses first class functions in Scala. It defines an even function that checks if a number is even and uses it to filter a list of numbers to return only the even ones. It also shows how functions can be passed as parameters to higher order functions like filter, find, exists, forall, and map. Closures are demonstrated where a function captures variables in its environment even if they are changed later. Tasks at the end instruct the reader to open a project and add tests to methods to practice first class functions.
6. Closures
val people = List(Person(“Alf”), Person(“Fredrik”))
val name = “Fredrik”
val nameFilter = (p: Person) => p.name == name
people.filter(nameFilter) // Person(“Fredrik”)
7. Closures
val people = List(Person(“Alf”), Person(“Fredrik”))
var name = “Fredrik”
val nameFilter = (p: Person) => p.name == name
people.filter(nameFilter) // Person(“Fredrik”)
name = “Alf”
people.filter(nameFilter) // Person(“Alf”)
8. Tasks (30 min)
Open the 'first-class-functions' project
Tests in package
scalaexamples.firstclassfunctions
Add @Test to one and one method
Follow instructions in the code
Make the tests pass
Editor's Notes
Vanskelig å forklare foldleft med flere parameter lister?