Scala ERROR: forward reference extends over definition of value xxx——错误解决方案

项目编译打包时的错误,有点莫名其妙。网上找了一些问题原因,稍微记录一下:

1,方法调用和定义间插入了val的定义

you're calling a method before you define it, and that the definition of the value x appears between that forward reference and the definition of the method. It is only legal to have forward references if there are no value definition between the reference and the referred method definiton。即在定义某方法之前调用了该方法,同时value xxxx定义出现在了调用和定义该方法之间。方法的调用若要出现在定义之前,二者之间就不能出现value定义。

这个我不是很理解啊,但大概意思是,下面这样使用f方法的调用和定义中间插入了一个val dummy=false就不行。

object Test {
  def main(args: Array[String]) {
    class NotUsed {val x = f}
    val dummy = false
    def f = true
  }
}

一个简单的解决方法是加一行注释(说出来你看你不信,但他们就是这么干的):

object Test {
  def main(args: Array[String]) {
    class NotUsed {val x = f}
    val dummy = false
    //add comment, make it lazy
    def f = true
  }
}

2,再一个原因: A val with the same name (like the function parameter) was declared later in the same function。就是命名冲突了,这个跟上一个原因其实很类似,一个是故意重复(调用和定义),一个是无意重复。总之呢,就是有问题,命名问题。

3,scala版本问题。这个说法呢,有一定道理,至少对我来说,这次bug到现在还没有找到语法方面的原因,不存在前面说的情况,反正就是莫名其妙地换了一个程序写法,就可以了,后来又换回之前的写法,发现居然也可以了……

问题困扰了个把小时,所以记下来,看看以后会不会用到。

猜你喜欢

转载自blog.csdn.net/hongxingabc/article/details/81636901