2

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?

noncom
  • 4,962
  • 3
  • 42
  • 70

2 Answers2

3

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.

agilesteel
  • 16,775
  • 6
  • 44
  • 55
1

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?

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • There is the following simplified example: imagine you have a class `Rule` which represents some rule applied to an object over a period of time which is called `duration`. There may be many children of that class, but I also want to have children like `RuleChain` and `RuleParallel`. These two classes may contain a set of rules executed sequentially or simultaneously, but treated exactly as `Rule`. As the `Rule` class takes `duration` as one of parameters, I have to pass the sum of durations for chain and the longest duration for parallel, thus I have to call some method. – noncom Feb 12 '12 at 07:47
  • 1
    @noncom What I don't understand is why you feel that method has to be in the class, not on the object, since it isn't about the instance. – Daniel C. Sobral Feb 12 '12 at 17:47
  • Yes, you are right, I just got used to think like that in Java, where there was no big difference. Here Scala enforces a more strict concern of application design and now I see it as a more correct one. With this in mind, it is obvious that the companion object is the best place for such methods. – noncom Feb 13 '12 at 05:39