I understand that subtyping works a little differently in Motoko than most languages I’m used to, being based on structrural subtyping as opposed to nominal subtyping. So I understand that the following will work just fine, and that Document’s root
member has no problem being either an ElementNode or a TextNode, even though neither of those declared that their “supertype” is Node, they just happen to share Node
's more general structure:
public class Document(prolog0: Text, root0: Node) {
var prolog: Text = prolog0;
var root: Node = root0;
};
public class Node(tag0: Text) {
var tag: Text = tag0;
};
public class ElementNode(tag0: Text, children0: [Node]) {
var tag: Text = tag0;
var children: [Node] = children0;
};
public class TextNode(tag0: Text, text0: Text) {
var tag: Text = tag0;
var text: Text = text0;
};
But that’s a lot of repeated code. I’d rather declare the tag
member in only one place, and call into that constructor from the subclass
constructors. Is there a way in Motoko to specify that ElementNode and TextNode should inherit the structure of the Node
class so I don’t need to redeclare that variable?
For example, I’d like to do something like this:
public class Node(tag0: Text) {
var tag: Text = tag0;
};
public class ElementNode(tag0: Text, children0: [Node]) : Node(tag0) {
var children: [Node] = children0;
};
public class TextNode(tag0: Text, text0: Text) : Node(tag0) {
var text: Text = text0;
};
That results in a syntax error, likely because it conflicts with the type annotation syntax used to specify the constructor’s return type.
Is superclass initialization possible in Motoko? Does that question even make sense with the way Motoko does things? What’s the best way to keep code like this DRY in Motoko?