从Java调用Scala“ val函数”给出错误

时间:2019-07-14 08:14:16

标签: java scala scala-java-interop

我有一个scala val函数,如下所示:

  val getTimestampEpochMillis = (year:Int, month:Int, day:Int, hour:Int, quarterHour:Int, minute:Int, seconds:Int) => {
    var tMinutes = minute
    var tSeconds = seconds
    if(minute == 0){
      if(quarterHour == 1){
        tMinutes = 22
        tSeconds = 30
      }else if(quarterHour == 2){
        tMinutes = 37
        tSeconds = 30
      }else if(quarterHour == 3){
        tMinutes = 52
        tSeconds = 30
      }else if(quarterHour == 0){
        tMinutes = 7
        tSeconds = 30
      }
    }

    val localDateTime = LocalDateTime.of(year, month, day, hour, tMinutes, tSeconds)
    localDateTime.atZone(ZoneId.of("GMT")).toInstant().toEpochMilli()
  }

当我从Java调用此函数时, 我收到以下错误:

[ERROR]   required: no arguments                                          
[ERROR]   found: int,int,int,int,int,int,int                              
[ERROR]   reason: actual and formal argument lists differ in length    

调用scala val函数的Java代码:

Long minTimestampOfGranularity = getTimestampEpochMillis(year, 1, 1, 0, 0, 0, 0);

1 个答案:

答案 0 :(得分:5)

尝试

getTimestampEpochMillis().apply(year, 1, 1, 0, 0, 0, 0);

并注意()中的括号getTimestampEpochMillis()。使用javap检查生成的类,我们得到

public scala.Function7<java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, scala.runtime.BoxedUnit> getTimestampEpochMillis();

我们看到getTimestampEpochMillis()返回scala.Function7的地方,因此我们必须先调用getTimestampEpochMillis()才能apply自变量。