RosettaCodeData/Task/Add-a-variable-to-a-class-instance-at-runtime/Ballerina/add-a-variable-to-a-class-instance-at-runtime.ballerina
2025-06-11 20:16:52 -04:00

23 lines
616 B
Text

import ballerina/io;
// Person is an 'open' record type which allows fields of 'anydata' type
// to be added at runtime.
type Person record {
string name;
int age;
};
public function main() {
// Create an instance of Person with an additional 'town' field.
Person p = {
name: "Fred",
age: 40,
"town": "Boston" // extra field name needs to be in quotes
};
// Print name and age fields - using standard '.' syntax.
io:print(p.name, " is ", p.age);
// Print the additional field - using a map-like syntax.
io:println(" and lives in ", p["town"], ".");
}