Add a variable to a class instance at runtime: Difference between revisions
Content added Content deleted
(→{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details) |
mNo edit summary |
||
Line 589: | Line 589: | ||
e.foo = 1 |
e.foo = 1 |
||
e["bar"] = 2 // name specified at runtime</lang> |
e["bar"] = 2 // name specified at runtime</lang> |
||
=={{header|Julia}}== |
|||
Julia does not allow direct modification of the data member variables of a type, |
|||
though class methods (just Julia functions) can be added without difficulty. |
|||
For special situations, such as when parsing an input file, where new data type names |
|||
may be appropriate, this can be accommodated using a Dict as one of the class variables. |
|||
For example, consider the below SOAP input data for a program processing phone numbers, |
|||
where the type of phone numbers for the person is unknown until run-time: |
|||
<lang xml> |
|||
{"phoneNumbers": [ |
|||
{ |
|||
"type": "home", |
|||
"number": "212 555-1234" |
|||
}, |
|||
{ |
|||
"type": "office", |
|||
"number": "646 555-4567" |
|||
}, |
|||
{ |
|||
"type": "mobile", |
|||
"number": "123 456-7890" |
|||
}]} |
|||
</lang> |
|||
Add the data into a class member that is declared as a Dict structure: |
|||
<lang Julia> |
|||
mutable struct Contact |
|||
name::String |
|||
phonenumber::Dict{Any,Any} |
|||
end |
|||
person = Contact("Jane Doe", Dict()) |
|||
person.phonenumber[home] = "212 555-1234" |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |