如何防止Feed处理程序的某些代码重复

时间:2016-04-28 07:39:08

标签: scala oop

我有一个Feed处理程序,如果更新的值与之前的值相同,我想再次阻止数据句柄,所以我有这样的代码

map.get(statisticsOpenAcronym).map { x =>
  var open = x.asInstanceOf[Number].doubleValue();
  if (statistics.open != open) {
    statistics.open = open;
    statistics.changed = true;
  }
}
map.get(statisticsCloseAcronym).map { x =>
  var close = x.asInstanceOf[Number].doubleValue();
  if (statistics.close != close) {
    statistics.close = close;
    statistics.changed = true;
  }
}

但是我需要一次又一次地复制[如果xxx不同,更新xxx并设置更改标志]。

只是想知道,我该如何防止这种情况?

1 个答案:

答案 0 :(得分:0)

你可以编写功能(我必须改变一些东西,因为我不确定你的类型):

case class Statistic() {
  var open = true
  var close = !open
  var changed = false
}

var statistics = Statistic()


def f(map: Map[String, String], statisticsOpenAcronym: String, statistic: Statistic, condition: Statistic => Boolean, exec: (Statistic, Boolean) => ()) = {
  map.get(statisticsOpenAcronym).map { x =>
    val close = x.asInstanceOf[Boolean]
    if (condition(statistic)) {
      exec(statistic, close)
    }
  }
}


def closeCondition(): Statistic => Boolean = { statistics: Statistic =>
  statistics.close
}

def closeStatistic(): (Statistic, Boolean) => Unit = { (statistics: Statistic, close: Boolean) =>
  statistics.close = close
  statistics.changed = true;
}


f(Map.empty, "acronym", statistics, closeCondition(), closeStatistic())

更好的是,您可以使closeStatistics返回包含所需参数的新统计信息,而不是Unit

开放案例是类似的。