'ambiguous type' error when defining a union of types having type inclusions

37 Views Asked by At

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.

1

There are 1 best solutions below

0
On

Because GenericPet is an open record, the mapping value with the specified four fields is also valid for GenericPet (in addition to Dog). 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:

  1. Use Closed Records: If GenericPet was a closed record, you would no longer observe the error. You can make GenericPet a closed record using the closed record syntax:

    type GenericPet record {|
        string name;
        int age;
        string breed;
    |};
    
  2. 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:

    Pet pet = <Dog> {
        name: "Mikey",
        age: 2,
        breed: "Dane",
        isTrained: false
    };