I have a record named GenericPet
with several fields. Another record named Dog
is a type inclusion of the record GenericPet
and also has its own field isTrained
. The type Pet
is a type union of both GenericPet
and Dog
. When I try to define an instance of Pet
in the following code segment, it throws the error: "ambiguous type".
type GenericPet record {
string name;
int age;
string breed;
};
type Dog record {
*GenericPet;
boolean isTrained;
};
type Pet GenericPet|Dog;
public function main() {
Pet myPet = {
name: "Mickey",
age: 2,
breed: "Dane",
isTrained: false
};
}
Is this behavior expected, and if so, why? Please clarify.
Because
GenericPet
is an open record, the mapping value with the specified four fields is also valid forGenericPet
(in addition toDog
). Therefore, the exact inherent type to use cannot be determined, leading to the "ambiguous type" error.If you want to resolve this ambiguity, you have a couple of options:
Use Closed Records: If
GenericPet
was a closed record, you would no longer observe the error. You can makeGenericPet
a closed record using the closed record syntax:Specify Type Using Type Cast Expression: Alternatively, you can specify the type to use as the inherent type using a type cast expression with the mapping constructor: