Reputation: 266
I have immutable classes Outer and Inner as follows:
class Outer(val intra: Outer#Inner) {
class Inner(val q: Int)
}
I want to create an instance of Outer and Inner which references each other, as follows:
val outer = new Outer(inner)
val inner = new outer.Inner(5)
However, of course, this code does not compile since the value "inner" is referenced in the first line before it is defined in second line.
And if I added "lazy" keywords before "val" keywords for those two lines, it compiles but it makes a stack overflow exception while running.
I know I can solve this problem if I make the class Outer mutable like this:
class Outer(var intra: Outer#Inner) {
class Inner(val q: Int)
}
val outer = new Outer()
val inner = new outer.Inner(5)
outer.intra = inner
But I want to keep the classes immutable. How can I solve this problem?
Upvotes: 1
Views: 112
Reputation: 32719
You can change your definitions like this:
class Outer(_intra: => Outer#Inner) {
lazy val intra = _intra
class Inner(val q: Int)
}
Upvotes: 2