Jump to content

Add a variable to a class instance at runtime: Difference between revisions

Added Oz.
(Added Oz.)
Line 199:
Here, the two 'variables' can be seen under the single heading 'f'. And of course all of this is done at runtime.
 
=={{header|Oz}}==
It is not possible to add variables to instances in Oz. Every object has exactly one class and this association cannot be changed after object creation. Classes themselves are immutable.
 
However, classes are also first-class values and are created at runtime. Many of the tasks that are solved with "monkeypatching" in other languages, can be solved by dynamically creating classes in Oz.
 
<lang oz>declare
%% Creates a new class derived from BaseClass
%% with an added feature (==public immutable attribute)
fun {AddFeature BaseClass FeatureName FeatureValue}
class DerivedClass from BaseClass
feat
%% "FeatureName" is escaped, otherwise a new variable
%% refering to a private feature would be created
!FeatureName:FeatureValue
end
in
DerivedClass
end
 
class Base
feat
bar:1
 
meth init
skip
end
end
 
Derived = {AddFeature Base foo 2}
 
Instance = {New Derived init}
in
{Show Instance.bar} %% inherited feature
{Show Instance.foo} %% feature of "synthesized" class</lang>
 
To add a variable number of features and attributes, you can use [http://www.mozart-oz.org/documentation/base/class.html Class.new].
=={{header|Perl}}==
{{works with|Perl|5.x}}
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.