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

Content added Content deleted
(omit from Applesoft BASIC, Brainfuck, Integer BASIC)
(→‎{{header|Groovy}}: new solution)
Line 235: Line 235:


dict[ 'newVar' ] = "I'm Rich In Data"</lang>
dict[ 'newVar' ] = "I'm Rich In Data"</lang>

=={{header|Groovy}}==

Any [[Groovy]] class that implements "''Object get(String)''" and "''void set(String, Object)''" will have the '''apparent''' capability to add new properties. However, this capability will only work as expected with an appropriate implementation, backed by a Map object or something very much like a Map.
<lang groovy>class A {
final x = { it + 25 }
private map = new HashMap()
Object get(String key) { map[key] }
void set(String key, Object value) { map[key] = value }
}</lang>

Test:
<lang groovy>def a = new A()
a.y = 55
a.z = { println (new Date()); Thread.sleep 5000 }

println a.x(25)
println a.y
(0..2).each(a.z)

println a.q</lang>

Output:
<pre>50
55
Wed Feb 23 21:33:40 CST 2011
Wed Feb 23 21:33:45 CST 2011
Wed Feb 23 21:33:50 CST 2011

null</pre>


=={{header|Io}}==
=={{header|Io}}==