proposal-first-class-protocols
proposal-first-class-protocols copied to clipboard
Traits based approach
I'd like to suggest a different approach for this proposal: instead of a class to implement protocols on declaration it will implement different protocols in a different statement for each protocol. This approach is known as Traits and can be seen in Scala, Rust, and other languages.
Traits enable better separation of concerns, composability, and are a static single solution for associating a protocol to a class, already declared (like Object) or not.
References:
Syntax
protocol ProtocolName {
// declare a symbol which must be implemented
requiredMethodName;
// and some methods that are provided by implementing this protocol
providedMethodName(...parameters) {
methodBody;
}
}
class ClassName {
}
implement ProtocolName for ClassName {
[ProtocolName.requiredMethodName]() {
// this is the implementation for this class
}
}
Example
protocol ToString {
tag;
toString() {
return `[object ${this[ToString.tag]}]`;
}
}
implement ToString for Object {
[ToString.tag] = "Object";
}