Jas*_*son 2 scala intellij-idea companion-object
我正在使用IntelliJ的Scala插件的最新版本并拥有以下代码片段,其目的是允许枚举类的实例Count:
class Count() {
val id = Count.id()
override def toString = s"Count$id"
}
object Count {
var n = -1
def id() = { n += 1; n }
}
println(Vector(new Count, new Count, new Count))
Run Code Online (Sandbox Code Playgroud)
当引用id()伴随对象的方法时,IntelliJ给我一个前向引用错误,但脚本编译完美,产生输出Vector(Count0, Count1, Count2).实际上,在成功运行脚本之后,我只是偶然发现了错误.是什么赋予了?
Scala工作表尝试单独编译每条指令.如果将所有代码包装到一个对象中(强制scala编译器整体使用整个代码) - 就不会出现这样的异常:
object a {
class Count() {
val id = Count.id()
override def toString = s"Count$id"
}
object Count {
var n = -1
def id() = {
n += 1; n
}
}
println(Vector(new Count, new Count, new Count))
}
Run Code Online (Sandbox Code Playgroud)