Tuesday, January 1, 2008

Wildcards observation

"A bug in poker is a limited form of wild card."
While looking for academic references for my properties project, I bumped into the expression problem - the write-up by Phil Wadler and follow-ups by Mads Torgersen and Matthias Zenger/Martin Odersky are really fun and educative readings.

This stuff caused me to re-read the the wildcards paper and I suddenly understood why I had this strange gut feeling about wildcard usage. Almost all learning material about Generics, including the wildcard paper itself, emphasizes the distinction between read and write methods - having a wildcard in a collection parameter prevents you from adding elements to the collection, but allows reading. This is true, but somewhat misleading. Actually, wildcard in the parameter allows us to call a method that returns the thing behind the wildcard and treat it as if the returned object is of the type of wildcard bound (or an Object, if the wildcard is unbound); the wildcard prevents us, however, from calling any method that takes "the thing behind the wildcard" as a parameter. Now obviously, to add something to a collection you need to call a method that takes that something as parameter, and it is indeed prevented, but other modifications are not disallowed, e.g. clear() .

The consequence of wildcard usage applies to any method, not just "write method", for example - containment test. So looking at Kevin's example, it now seems to me that doSomeReading method shouldn't have used a wildcard if it wished to perform a safe containment test - that's the catch (or should I say, hm, capture...)

Happy New Year!

1 comment:

a term paper service said...

Looks like not just the formal type parameters in the generic unit, but also wildcards can be constrained if someone doesn't want to be compatible to all instantiations