ballerina-spec
ballerina-spec copied to clipboard
String representations of a Type
Description: A human-readable string representation of a type is mostly required for generating type-related error messages in both compile-time and runtime. There is a slight inconsistency in the current implementation when dealing with type descriptors vs. type definition.
type Person record {|
string name;
int age;
|};
public function main() {
Person p = {name : "tom", age : 10};
record {|
string name;
float age; // <- Wrong type.
|} q = p; // Compilation error.
}
Above code generates the following the compilation error.
incompatible types: expected '$anonType$0', found 'Person'
The developer can't figure out what went wrong here. We can improve the error message by providing the type information.
e.g.
// Option 1:
incompatible types: expected 'record {| string name; float age; |}', found 'Person'
// Options 2:
incompatible types: expected 'record {| string name; float age; |}', found 'record {| string name; int age; |}'
This raises a few questions:
- That is the string representation of a type?
- One possible solution is to use type descriptor like syntax.
- Should we use type definition names if possible?
- Should this be part of the spec?
If you have a recursive type e.g.
type List record {
int n;
List? next;
};
you cannot write it without using a name.
Yes, you are correct. One option is to refer type definitions using type name itself. i.e., List
Some of the papers that I have read on semantic subtyping suggest based on their experience that in a case where you have a type S that is supposed to be a subtype of a type T, but fails to be, it is helpful to give an example of a value that it is in S but not in T.