Skip to content

Instantly share code, notes, and snippets.

@landonf
Created August 10, 2009 19:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save landonf/165365 to your computer and use it in GitHub Desktop.
Save landonf/165365 to your computer and use it in GitHub Desktop.
In some cases the type of a method's result may depend on the type of its arguments.
To accurately express the signatures of such methods one may use parametric polymorphism.
A parametrically polymorphic method signature introduces one or more formal type arguments
which can be used throughout the signature and the method body. When the message is sent,
the actual types will be inferred and replace the formal type arguments in the signature.
As an example, consider the signature of -[NSArray[T] mapArrayUsingBlock:]
- (NSArray[X]) mapArrayUsingBlock: (X (^)(T obj) block;
The type term X def introduces a type argument X, which will be inferred to be the type returned
by the block. A typical usage would be
NSArray[NSNumber] *nums = [NSArray arrayWithObject: [NSNumber numberWithInt: 42]];
NSArray[String] *strings = [nums mapArrayUsingBlock: ^(NSNumber *number) {
return [number stringValue];
}];
Here X will be inferred to be NSString, and thus return type of the mapArrayUsingBlock: is NSArray[NSString].
The block argument 'number' is type checked and optionally inferred from nums' NSArray[T] type parameter.
If Obj-Not-C were to support local type inference, the following version could be type checked, and less verbose:
nums = [NSArray arrayWithObject: [NSNumber numberWithInt: 42]];
strings = [nums mapArrayUsingBlock: ^(number) {
return [number stringValue];
}];
The nums variable is inferred as NSArray[NSNumber], strings is inferred as NSArray[String], 'number' block argument is inferred as 'NSNumber'.
To implement this, +[NSArray arrayWithObject] would use something like the following type signature:
+ (NSArray[T]) arrayWithObject: T object;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment