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
答案 0 :(得分:1)
一些事情:
plusMonths
等采用长参数后,stepFunc
的类型应为stepFunc:(LocalDate, Long) => LocalDate
stepFunc
不是LocalDate
上的方法,而是一个函数。而是使用stepFunc(oldDate, if (forward) num else -num)
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实现并且不是静态函数,我们需要创建它的对象,然后将其作为部分应用的函数传递。经典斯卡拉!