Reputation: 1637
I am trying to replicate my problem on a smaller example. I am getting compilation error at the shown location in the following code snippet.
class Outer {
class Inner
}
object OuterUtil {
val obj = new Outer
object xyz extends obj.Inner
//do something with xyz
}
//-------------------
object OuterUtil2 {
var m_obj: Outer = null
def createOuter() = {
m_obj = new Outer
}
def anotherMethod() {
//Compilation error here: stable identifier required,
//but OuterUtil2.this.m_obj found.
object xyz extends m_obj.Inner
}
}
object Test {
OuterUtil2.createOuter
OuterUtil2.anotherMethod
}
OuterUtil
is working fine.
In OuterUtil2
, I am splitting the functionality into two functions. I am storing the Outer
instance m_obj
as a member var
. The createOuter
method creates and stores the Outer
instance in m_obj
. In anotherMethod
, I am getting compilation error. How to fix OuterUtil2
?
Upvotes: 1
Views: 234
Reputation: 15325
If you just want to solve the problem with your function, here is a solution (by fixing the var
to a val
in the function)
def anotherMethod = {
val obj = m_obj
new obj.Inner
}
Another solution would be to use some options, however to overpass the stable identifier method, you have to define a val
out of m_obj
value. This solution is more elegant because you don't have null pointer exceptions if m_obj
is not defined.
object OuterUtil2 {
var m_obj: Option[Outer] = None
def createOuter {
m_obj = Some(new Outer)
}
def anotherMethod = {
m_obj match{
case None => None
case Some(_) => val obj = m_obj.get; Some(new obj.Inner)
}
}
}
Upvotes: 1
Reputation: 55028
The prefix of a type (ie, the m_obj
in m_obj.Inner
) must be a stable value; a var
doesn't cut it. You could make that a val
and move the initialization out of createOuter
.
Upvotes: 3