Objective-C Method Overload

I have doubts about overloading the Objective-C method. Java supports method overloads with the same name, as many arguments of different types. But when I try to make a similar declaration in Objective-C, it gives me the Duplicate method declaration error. Consider the following code:

/* Java */ int add(int i, int j); int add(int i, int j, int k); // Accepted float add(float i, float j); // Accepted /* Objective-C */ - (int)add:(int)i and:(int)j; - (int)add:(int)i and:(int)j and:(int)k; // Accepted - (float)add:(float)i and:(float)j; // Throws error 

Why is this not supported in Objective-C? Is there an alternative for this?

+7
source share
2 answers

It is simply not supported in Objective-C. It was not supported in regular old C, so it is not surprising that Objective-C did not add method overloads either. For clarity, this can sometimes be good. Typically, the way around this is to include some parameter information in the function name. Example:

 - (int) addInt:(int)i toInt:(int)j; - (int) addInt:(int)i toInt:(int)j andInt:(int)k; - (float) addFloat:(float)i toFloat:(float)j; 
+15
source

Starting from this:

 - (int)add:(int)i and:(int)j; 

This does not negate anything - this is another method:

 - (int)add:(int)i and:(int)j and:(int)k; // Accepted 

The following is not acceptable: Objective-C does not allow declarations with a covariant or contravariant method. In addition, Objective-C makes forwarding based on the forwarding type a la Java and C ++.

 - (float)add:(float)i and:(float)j; // Throws error 

Note that Java is derived directly from Objective-C.

+6
source

All Articles