Search code examples
ballerina

Error when overriding common field (included field) in a ballerina record


I'm getting an error when trying to override a common field (included field) in one record with a different type in ballerina. Please refer to the below code.

type Vehicle record {
    string color;
    string fuel;
};

type Car record {
    *Vehicle;
    FuelType fuel; // Getting error here
};

type FuelType record  {
    boolean petrol;
    boolean diesel;
};

I have two records named Vehicle and Car, where Car includes Vehicle. When I override the common field fuel from string type to a record type FuelType, I get the following error:

included field 'fuel' of type 'string' cannot be overridden by a field of type 'FuelType': expected a subtype of 'string'.

However, when I override it with an enum FuelTypeEnum, there is no error. Why am I getting two different behaviors?

type Car record {
    *Vehicle;
    FuelTypeEnum fuel; // No error here
};

enum FuelTypeEnum {
    petrol,
    diesel
};

Solution

  • By design, we require overriding fields to use a type, that is a subtype of the overridden field's type. Therefore, the type of fuel in Car has to be a subtype of string. i.e. the type of fuel in the included record (Vehicle here) will have to be the broader (super) type.

    In the second case, an enum is a union of string constants. i.e. The above FuelTypeEnum enum is equivalent to,

    const petrol = "petrol";
    const diesel = "diesel";
    type FuelTypeEnum petrol|diesel; 
    

    Therefore, FuelTypeEnum is a subtype of a string. Therefore, we can use that to override the field type.