Random "if it bends it is funny, if it breaks it isn't funny" line of thought

I was wondering how something like duck typing might work in C# or Java (there are other strict languages which do support duck typing, O'Caml for instance). Seems like you would have to have lots of interfaces and then list them when implementing them. Basically every public method would have an interface describing it, and then each class would laboriously list all those interfaces.

Actually it all falls apart because I don't think one can say a method takes a set of interfaces for a single parameter. You would have to automatically generate the combinatorical set of interface mixins, and use those in the method signitures.

(Just musing over the range of things one could - not particularly want to - do with the way Java/C# are already defined.)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Safe Structural Conformance for Java

Something like this has been done in the paper "Safe Structural Conformance for Java" by Läufer, Baumgartner, and Russo. I don't remember the details exactly, so I cannot give a quick impression of the (dis)advantages right now. If you search for papers that cite this work, then you'll probably find more recent work, for example "Implementing Dynamic Language Features in Java using Dynamic Code".

Been there, done that

I blogged about static duck typing in Java using generics some time back:

My Blog.

I've worked with this solution for a while, and decided that without tool support it's not so much fun. My IDE cannot tell me when a type bound is unused, e.g., if I declare a parameter to be able to walk and quack, and all the method does is make it walk (the quack part is unused).

Reflection

You can use reflection in C# or Java to grab a method by name and execute it dynamically. That's probably more similar to the intent of duck typing than building out all kinds of interfaces. Of course you lose any of the (perceived) benefits of static typing, have potential for runtime errors, etc.

funny

I thought the purpose of "duck typing" was to have a more concise and flexible way of passing parameters. Then i hear this:

"Basically every public method would have an interface describing it, and then each class would laboriously list all those interfaces."

yeah, you save some typing by not describing the types, but then has a lot of lists attached. very funny, indeed...

Some may find flexibility

Some may find flexibility more important than conciseness.

Either way

It would seem like this idea would require a pre-javac-system to make it actually usable in any way, to try to a) generate the combinatorical explosion of interfaces and b) to automatically insert those or make manual use of them somehow easier.

Which probably means one should just use something like Scala instead? ;-)