Friday, January 28, 2011

Rosseta code tutorials:Add a variable to a class instance at run-time

Another Rosetta code sample here

Though ELENA does not support adding a function / variable at a run time this could be simulated with the help of a group object (Note that ELENA does not allow a direct access to the object fields at all).

So we have to create a group member FieldContainer which will hold the variable and a pair of the methods to access it (get / set).

First of we have to declare a new subject (a property name) - foo
#subject foo.

Then a property container:
#class FieldContainer
#field theValue.

#method foo'set : anObject
theValue := anObject.

#method foo'get = theValue.

So now we could extends any existing object
// adding a field
anObject := #group(anObject, FieldContainer).

anObject set &foo:"bar".

#var aConstant := #group("My String", FieldContainer).
aConstant set &foo:"boo".

'program'Output << anObject foo.


  1. I did not understand a thing
    Why I have to create the Object class?

  2. No, the general idea is to extend any existing object with a new property, which I called foo. Object class is a bad example, I must admit. So I will replace it with a numeric constant:

    #var anObject := 234.

    // adding a field
    anObject := #group(anObject,FieldContainer).

    anObject set &foo:"bar".

    'program'Output << anObject foo.