I know that .Net 4 is going to have some pretty cool features around dynamic typing and C++0x is also adding some auto typing features. I was thinking about all of this today and realized that what I really use most of the time is an inferred type. Essentially it would infer a new type based on the method’s contents.
Let’s say we have this:
public void callSomeMethod(Object obj) {
obj.methodCall();
}
In static languages this fails because Object doesn’t contain the method methodCall. However, what if we told the compiler to create a new interface based on the content of the method? This code would then look like this:
public void callSomeMethod(autotype obj) {
obj.methodCall();
}
The autotype keyword would cause the compiler to actually create this code:
public interface MethodCallInterface {
void methodCall();
}
public void callSomeMethod(MethodCallInterface obj) {
obj.methodCall();
}
This would now compile. Next, a caller to this method could pass in any object whose type the compiler could add this interface to. If you called it like this:
public class MyClass {
public void methodCall() {
System.out.println("Here I am");
}
}
// Some other code somewhere
MyClass mc = new MyClass();
callSomeMethod(mc);
The compiler could take the interface it created for this method call and then see if the type passed in could implement that interface. If MyClass has already been compiled, it could do one of two things:
- If MyClass is accesible as part of the current compilation unit, it could update the compiled Class to implement the interface
- If it isn’t part of the current compilation unit and isn’t final, it could create a proxy for the call that implements the interface and delegates the call
Not sure yet how #2 really works or if it even makes sense to do it that way, but it seems to be the only way to make it work if the Class is in a JAR or DLL or something like that.
The only issue would be reflection. How could you reflection on the method and then pass an Object to it so that it would not completely blow chunks at runtime? Perhaps the reflective method invocation could determine if the object being passed could be proxied to the dynamic interface and then create a proxy on the fly.
Anyways, just pondering type systems in general today….