Reputation: 1427
The university example explains how to update all items of a map:
(allLecturers composeLens salary).modify(_ + 2)(uni)
To set a single item, one can use this cumbersome code:
(departments composeLens at("History")).set(Some(Department(30, List(Lecturer("arnold", "stones", 30)))))(uni)
To update a single item, I wrote:
def updateBudget(department: Option[Department]): Option[Department] = {
val budgetLens = GenLens[Department](_.budget)
Some(budgetLens.set(40)(department.get))
}
(departments composeLens at("History")).modify(updateBudget)(uni)
Is there a more elegant syntax for this?
With Lists, the Optionals are not necessary:
val lecturers = GenLens[Department](_.lecturers)
def updateSalary(lecturer: Lecturer): Lecturer =
GenLens[Lecturer](_.salary).set(40)(lecturer)
(lecturers composeOptional index(0)).modify(updateSalary)(dep)
Or, even more compact:
(lecturers composeOptional index(0)).modify((l: Lecturer) => l.lens(_.salary).set(40))(dep)
Upvotes: 1
Views: 174