I'm using the latest version of IntelliJ's Scala plugin and have this following piece of code, the aim of which is to allow enumeration of the instances of class 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))
When referencing the method id()
of the companion object, IntelliJ gives me a forward reference error, yet the script compiles perfectly, producing the output Vector(Count0, Count1, Count2)
. In fact, I only noticed the error by chance, after running the script successfully. What gives?
Scala worksheets attempt to compile each instruction separately. If you wrap all your code into one object (to force scala compiler work with whole code integrally) - there will be no such exception:
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))
}