我需要根据复杂的逻辑更新案例类的实例。我随附的内容:
case class Thing(i: Int, s: String) {
def map(f: Thing => Thing): Thing = f(this)
}
def update1(thing: Thing) = {
var x = thing
if (true) x = x.copy(i = x.i + 3)
if (true) x = x.copy(s = x.s.trim)
if (true) x = x.copy(i = x.i * 7)
x
}
def update2(thing: Thing) = {
val x1 = if (true) thing.copy(i = thing.i + 3) else thing
val x2 = if (true) x1.copy(s = x1.s.trim) else x1
if (true) x2.copy(i = x2.i * 7) else x2
}
def update3(thing: Thing) = {
def up1(x: Thing) = if (true) x.copy(i = x.i + 3) else x
def up2(x: Thing) = if (true) x.copy(s = x.s.trim) else x
def up3(x: Thing) = if (true) x.copy(i = x.i * 7) else x
(up1 _).compose(up2).compose(up3)(thing)
}
def update4(thing: Thing) =
thing
.map { x => if (true) x.copy(i = x.i + 3) else x }
.map { x => if (true) x.copy(s = x.s.trim) else x }
.map { x => if (true) x.copy(i = x.i * 7) else x }
if (true)
可能是复杂的if..else
或match
等。
除最后一个变量外,我不喜欢其他所有变量,但它需要map
函数定义,这不是很好(方法并不完全通用)。另外请注意,Thing
不是通用的,因此我不需要Functor
实例+ Cats等。
此任务有惯用的方式吗?
答案 0 :(得分:0)
怎么样?
val myThing = Thing(1, "destroy all monsters")
val conditionUpdates: Seq[(() => Boolean, Thing => Thing)] = ???
val conditionallyUpdatedThing = conditionUpdates.foldLeft(myThing){
case(thingAcc, (condition, update)) =>
if(condition())
update(thingAcc)
else
thingUpdate
}
优点是您可以根据需要传递尽可能多的条件更新。