Scala:传递plusMonth / plusYear函数作为参数

时间:2013-11-21 07:18:31

标签: function scala date arguments

plusMonths / plusYears是类LocalDate的函数。基于我对'checkEOM'函数的要求,我想将它们作为参数传递。我的功能如下:

  protected def checkEOM(oldDate:LocalDate, stepFunc:(LocalDate) =>LocalDate, step:Int, forward:Boolean):LocalDate = {
      val newDate = oldDate.stepFunc(if (forward) step else -step)
      val yearNew = newDate.getYear
      val monthNew = newDate.getMonthValue
      if (oldDate.getDayOfMonth == getLastDayOfMonth(oldDate.getYear, oldDate.getMonthValue)) 
          LocalDate.of(yearNew, monthNew, getLastDayOfMonth(yearNew, monthNew))
      else
          newDate
}

它基本上检查给定的'oldDate'是否是月末日期。如果是,那么根据'stepFunc'中传递的函数(即plusMonths或plusYears),我们得到'newDate'或newdate的EOM。我如何正确地将它们作为参数传递?我现在收到以下错误:

value stepFunc is not a member of javax.time.LocalDate

2 个答案:

答案 0 :(得分:1)

一些事情:

  1. plusMonths等采用长参数后,stepFunc的类型应为stepFunc:(LocalDate, Long) => LocalDate
  2. 要调用step func,您不能使用方法调用语法,因为stepFunc不是LocalDate上的方法,而是一个函数。而是使用stepFunc(oldDate, if (forward) num else -num)
  3. 当您致电checkEOM时,请确保将plusMonths等传递为正确类型的匿名函数。例如。 checkEOM(oldDate, _.plusMonths(_), ...

答案 1 :(得分:0)

我想我明白了。这是正确的实施:

 protected def checkEOM(oldDate:LocalDate, stepFunc:(Int =>LocalDate), step:Int, forward:Boolean):LocalDate = {
  val newDate = stepFunc(if (forward) step else -step)
  val yearNew = newDate.getYear
  val monthNew = newDate.getMonthValue
  if (oldDate.getDayOfMonth == getLastDayOfMonth(oldDate.getYear, oldDate.getMonthValue)) 
LocalDate.of(yearNew, monthNew, getLastDayOfMonth(yearNew, monthNew))
   else
    newDate
}

这是正确的致电方式:

checkEOM(date, date.plusMonths(_), num, forward, holidays)

由于plusDays()已经用Java实现并且不是静态函数,我们需要创建它的对象,然后将其作为部分应用的函数传递。经典斯卡拉!