我正在使用最新版本的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))
当引用伴随对象的方法id()
时,IntelliJ会给我一个前向引用错误,但脚本编译完美,产生输出Vector(Count0, Count1, Count2)
。实际上,在成功运行脚本之后,我只是偶然发现了错误。是什么给了什么?
答案 0 :(得分:5)
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))
}