Add a variable to a class instance at runtime
You can add variables/methods to a class at runtime by composing in a role. The role only affects that instance, though it is inheritable. An object created from an existing object will inherit any roles composed in with values set to those at the time the role was created. If you want to keep changed values in the new object, clone it instead.
That's what's going on underneath, but often people just mix in an anonymous role directly using the but
operator. Here we'll mix an attribute into a normal integer.
On the other hand, mixins are frowned upon when it is possible to compose roles directly into classes (as with Smalltalk traits), so that you get method collision detection at compile time. If you want to change a class at run time, you can also use monkey patching:
This practice, though allowed, is considered to be Evil Action at a Distance.
Last updated
Was this helpful?