Reputation: 4992
Suppose I have the following Scala code:
class Foo(a: Int)
class Bar(b: Buffer[Int]) extends Foo (sum) {
def sum = (1 /: b)(_ + _)
}
why does it complain on calling the method sum
from the constructor? Is it not possible to get such a behavior with such simple implementation at all? I realize that I could make a companion object for Bar
but that is not exactlywhat would I do?
PS there is no 'superconstructor' tag!)))
UPDATE: What are possible alternatives?
Upvotes: 2
Views: 420
Reputation: 297265
if sum
is not being called on a Bar
instance -- and it isn't, since it hasn't been constructed yet! -- then its place is definitely not inside Bar
. If Bar
is its sole user, then the natural place for it is the companion object.
The more interesting question is why you don't want it in its natural place?
Upvotes: 1
Reputation: 16859
Each time an instance of Bar
is being constructed all its members are being added to it. Only after the construction is complete can you call its members.
Upvotes: 3