native icon indicating copy to clipboard operation
native copied to clipboard

Does anyone need to implement protocol class methods?

Open liamappelbe opened this issue 1 year ago • 1 comments
trafficstars

My initial design for implementing ObjC protocols from Dart will only support instance methods. This is the use case most Dart programmers will be familiar with, analogous to implementing the methods of an interface.

But in ObjC, protocols can also contain class methods (analogous to static methods in Dart). It's possible to implement them, and for a consumer of the protocol to get the instance's class and then call the implementation of that class method:

@protocol MyProtocol<NSObject>
+ (double)classMethod;
@end


@interface ObjCProtocolImpl : NSObject<MyProtocol>
@end

@implementation ObjCProtocolImpl
+ (double) classMethod {
  return 1.23;
}
@end


@interface ProtocolConsumer : NSObject
- (double)callClassMethod:(id<MyProtocol>)proto;
@end

@implementation ProtocolConsumer : NSObject
- (double)callClassMethod:(id<MyProtocol>)proto {
  Class cls = [proto class];
  return [cls classMethod];  // Returns 1.23
}
@end

Supporting this would be tricky, and I think that protocols with class methods are rare. So for now I'm not going to support it. Comment on this issue if you have a use case.

liamappelbe avatar May 16 '24 01:05 liamappelbe

Off-topic: I've wanted to have virtual statics and virtual constructors in Dart for a long time (https://github.com/dart-lang/language/issues/356)! Cool to see that Objective-C has them.

dcharkes avatar May 17 '24 08:05 dcharkes