-
Notifications
You must be signed in to change notification settings - Fork 8
Description
This is somewhat related to #13, except #13 is about class-wide initialization logic, whereas this is about per-instance initialization logic.
In my experience implementing protocol-like patterns for years, it is exceedingly common to need to run some kind of initialization logic on each instance, and since constructors are immutable, it is currently impossible without consumer involvement.
Since constructor is not a valid member name anyway (#57), I wonder if protocols could support a special constructor() provided member that would allow them to run constructor initialization logic. This would run before the host class constructor logic, but after the superclass constructor.
In terms of prior art, it appears that this is possible in many languages that support traits/interfaces/partials, though far from all:
- Ruby mixins (via
initialize) - Python (via
super()) - Dart: fields with initializers
- Scala traits
Do note that if we support class fields with initializers as provided members (see #49 (comment) ) then constructor side effects become possible, just a little annoying. Most of the languages that do not support constructor side effects on principle seem to also not support fields.
That said, if this were possible, one can add constructor side effects to literally any class, including built-ins, by creating and implementing a dummy protocol, and monitor every created instance which seems undesirable for a variety of reasons. So perhaps it should require some kind of double handshake, though ideally not O(N) on the number of protocols.