1

大学示例解释了如何更新地图的所有项目:

(allLecturers composeLens salary).modify(_ + 2)(uni)

设置单个项目,可以使用这个繁琐的代码:

(departments composeLens at("History")).set(Some(Department(30, List(Lecturer("arnold", "stones", 30)))))(uni)

为了更新单个项目,我写道:

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)

有没有更优雅的语法?


使用列表,选项不是必需的:

val lecturers = GenLens[Department](_.lecturers)

def updateSalary(lecturer: Lecturer): Lecturer =
    GenLens[Lecturer](_.salary).set(40)(lecturer)

(lecturers composeOptional index(0)).modify(updateSalary)(dep)

或者,更紧凑:

(lecturers composeOptional index(0)).modify((l: Lecturer) => l.lens(_.salary).set(40))(dep)
4

0 回答 0