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

Content added Content deleted
(Improved first D entry)
No edit summary
Line 809: Line 809:


"class << e" uses the ''singleton class'' of "e", which is an automatic subclass of Empty that has only this single instance. Therefore we added the "foo" accessor only to "e", not to other instances of Empty.
"class << e" uses the ''singleton class'' of "e", which is an automatic subclass of Empty that has only this single instance. Therefore we added the "foo" accessor only to "e", not to other instances of Empty.

=={{header|Scala}}==
{{works with|Scala|2.10}}
Since version 2.10 Scala supports dynamic types. Dynamic types have to implement trait ''Dynamic'' and implement methods ''selectDynamic'' and ''updateDynamic''.

<lang scala>import language.dynamics
import scala.collection.mutable.HashMap

class A extends Dynamic {
private val map = new HashMap[String, Any]
def selectDynamic(name: String): Any = {
return map(name)
}
def updateDynamic(name:String)(value: Any) = {
map(name) = value
}
}</lang>

Sample output in the REPL:

<lang scala>scala> val a = new A
a: A = A@7b20f29d

scala> a.foo = 42
a.foo: Any = 42

scala> a.foo
res10: Any = 42</lang>


=={{header|Slate}}==
=={{header|Slate}}==
Line 974: Line 1,002:
{{omit from|PureBasic}}
{{omit from|PureBasic}}
{{omit from|R}}
{{omit from|R}}
{{omit from|Scala}}
{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} <!-- Does not have objects. -->
{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} <!-- Does not have objects. -->
{{omit from|Retro}}
{{omit from|Retro}}