Jump to content

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

No edit summary
Line 270:
e := Empty clone
e foo := 1</lang>
 
=={{header|Icon}} and {{header|Unicon}}==
{{omit from|Icon}}
Unicon implements object environments with records and supporting procedures for creation, initialization, and methods. To modify an instance you must create a new record then copy and amend it. The procedures ''constructor'' and ''fieldnames'' are needed. This example doesn't do error checking. Here ''extend'' takes three arguments, the class instance, a list of new variable names as strings, and an optional list of new values to be assigned.
 
''Note:'' Unicon can be translated via a command line switch into icon which allows for classes to be shared with Icon code (assuming no other incompatibilities exist).
<lang unicon>
link ximage
 
procedure main()
c1 := foo(1,2) # instance of foo
write("c1:\n",ximage(c1))
c1 := extend(c1,["c","d"],[8,9]) # 2 new fields
write("new c1:\n",ximage(c1))
c1 := extend(c1,["e"],[7]) # 1 more
write("newest c1:\n",ximage(c1))
end
 
class foo(a,b) # dummy class
end
 
procedure extend(instance,newvars,newvals) #: extend a class instance
every put(f := [],fieldnames(instance)) # copy existing fieldnames
c := ["tempconstructor"] ||| f # new constructor
every put(c,!newvars) # append new vars
t := constructor!c # new constructor
x := t() # new instance
every x[v := !f] := instance[v] # same as old instance
x.__s := x # new self
if \newvals then
every i := 1 to min(*newvars,*newvals) do
x[newvars[i]] := newvals[i] # add new vars = values
return x
end</lang>
 
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/ximage.icn ximage.icn provides ximage to dump variable contents]
 
Output:<pre>c1:
R_foo__state_1 := foo__state()
R_foo__state_1.a := 1
R_foo__state_1.b := 2
new c1:
R_tempconstructor_1 := tempconstructor()
R_tempconstructor_1.__s := R_tempconstructor_1
R_tempconstructor_1.__m := R_foo__methods_1 := foo__methods()
R_tempconstructor_1.a := 1
R_tempconstructor_1.b := 2
R_tempconstructor_1.c := 8
R_tempconstructor_1.d := 9
newest c1:
R_tempconstructor_1 := tempconstructor()
R_tempconstructor_1.__s := R_tempconstructor_1
R_tempconstructor_1.__m := R_foo__methods_1 := foo__methods()
R_tempconstructor_1.a := 1
R_tempconstructor_1.b := 2
R_tempconstructor_1.c := 8
R_tempconstructor_1.d := 9
R_tempconstructor_1.e := 7</pre>
 
 
=={{header|J}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.