复杂案例类实例更新

时间:2018-11-13 13:40:18

标签: scala

我需要根据复杂的逻辑更新案例类的实例。我随附的内容:

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..elsematch等。

除最后一个变量外,我不喜欢其他所有变量,但它需要map函数定义,这不是很好(方法并不完全通用)。另外请注意,Thing不是通用的,因此我不需要Functor实例+ Cats等。

此任务有惯用的方式吗?

1 个答案:

答案 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
}

优点是您可以根据需要传递尽可能多的条件更新。