import ballerina/io;public type Person record {
string name;
int age;
object {
public string city;
public string country; public function __init(string city, string country) {
self.city = city;
self.country = country;
} public function value() returns string {
return self.city + ", " + self.country;
}
} address;
};public function main() {
Person john = {
name: "John Doe",
age: 25,
address: new("Colombo", "Sri Lanka")
};
io:println(john.address.city);
object {
public string city;
public string country; public function __init(string city, string country) {
self.city = city;
self.country = country;
} public function value() returns string {
return self.city + ", " + self.country;
}
} adr = new("London", "UK"); Person jane = { name: "Jane Doe", age: 20, address: adr };
io:println(jane.address.country);
}
Anonymous ObjectsObject types can be defined in-line as well. These types do not have a type name associated with them. Such anonymous object types can be used in instances in which there is no need to refer to the object type by its name (e.g., objects as fields of records or objects or objects as function parameters). |
|
|
|
|
|
This is an anonymous object type descriptor. All the fields and methods are made public. This is done to allow the declaration of variables equivalent to this object type (since two public object types are considered unequivalent if either of the objects have any private members). |
|
|
|
|
|
|
|
There is no difference in how objects of anonymous types are created. |
|
Since anonymous objects do not have a type name associated with them, the object descriptor itself has to be specified when declaring variables of an anonymous object type. |
|
|
|
|
|
|