Writing Classes: init & new clarification needed

I’ve always found this to be a painful area of SC, I suppose you could pass extra arguments through to the the underlying newCopyArgs. One problem arises with multiple levels of inheritance and ensuring the instance variable goes in the correct place.

A little while ago a submitted two prs relevant to this, one was redoing the implementation of keywords args, and the other was making newCopyArgs work with keywords arguments. Together you could do something like the following… (Away from pc so can’t test but this should work)…

Base {
   var a, b;
   *new { |a, b ...args, kwargs| 
      ... some initialisation logic with a and b
      ... Check args is empty or throw 
      ^this.performArgsSuper(\newCopyArgs, [a, b], kwargs)
   }
}

Derived : Base {
   var c;
   *new { |a, b, c... args, kwargs| 
      ^this.performArgsSuper(\new, [a, b] ++ args, [\c, c] ++ kwargs)
   }  
}

This way, you can assign to c, without requiring it to be public, and you don’t need to worry about the instance variable ordering because they are set by name. This approach doesn’t solve issues of running extra initialisation logic though.

1 Like