Thursday, January 25, 2007

dynamic typing within a statically typed language

There were a lot of discussion about dynamically vs. statically typed languages the last two years. I wonder if statically typed languages should come up with some "unsafe" untyped constructs (as most of them are already unsafe, because they support casts). Take Java for example. Typically you need to write a lot of ugly reflection code if you want to invoke a method dynamically:

Class c = obj.getClass();
Method m = c.getMethod(name,new Class[]{param1.getClass(),param2.getClass()});
Object result = m.invoke(obj,new Object[]{param1,param2});

If there were some syntactic sugar for dynamic invocation of methods, it would become much shorter and more readable.
Maybe something like this (note the two colons),param2)

As the return value is always untyped (i.e. of type Object) I don't want to cast it down, but rather let the language infer the type and implicitely cast it down (it's unsafe anyway).

Person p = obj..getPerson();
// instead of
Person p = (Person) obj..getPerson();

What if a method doesn't exist? Usually a MethodNotFoundException would be thrown, but I would like to have a methodNotFound() method defined on java.lang.Object (defaultimpl throws MNE), which is called instead and can be overwritten. The following should illustrate what I mean:

class Stuff {
protected Object methodNotFound(String name, Object[] params) {
return this;
public static void main(....) {
new Stuff()..hello();
// where ..hello() is a shortcut for .."hello"()

output: hello,world,bla

Of course, this doesn't allow real metaprogramming or similar things, but would make generic code more readable, wouldn't it.
And keep down, these are just some thoughts, I wouldn't add it to Java if I could. Just loud thinking.

BTW.: many features of Ruby or Python everybody loves, like closures or the loose invocation syntax are not restricted to dynamic typing. If you are interested in these things you should definitely have a look at the C#3.0 specs. C#3.0 will have a number of really cool new features! Another language called Scala looks really promising, too.