Jump to content

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

Added Wren
(Added Wren)
Line 1,818:
% $s2 value time
can't read "time": no such variable</lang>
 
=={{header|Wren}}==
Although Wren is dynamically typed, it is not possible to add new variables (or fields as we prefer to call them) to a class at run time. We therefore follow the example of some of the other languages here and use a map field instead.
<lang ecmascript>import "io" for Stdin, Stdout
 
class Birds {
construct new(userFields) {
_userFields = userFields
}
userFields { _userFields }
}
 
var userFields = {}
System.print("Enter three fields to add to the Birds class:")
for (i in 0..2) {
System.write("\n name : ")
Stdout.flush()
var name = Stdin.readLine()
System.write(" value: ")
Stdout.flush()
var value = Num.fromString(Stdin.readLine())
userFields[name] = value
}
 
var birds = Birds.new(userFields)
 
System.print("\nYour fields are:\n")
for (kv in birds.userFields) {
System.print(" %(kv.key) = %(kv.value)")
}</lang>
 
{{out}}
Sample session:
<pre>
Enter three fields to add to the Birds class:
 
name : finch
value: 6
 
name : magpie
value: 7
 
name : wren
value: 8
 
Your fields are:
 
finch = 6
magpie = 7
wren = 8
</pre>
 
=={{header|zkl}}==
9,490

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.