Groovy is clearly not a statically typed language.
I recently wrote about how undetected type errors when using languages like Ruby and Python can be quite dangerous. That article has gotten some notice, with one response considering Groovy.
The article about Groovy purports to have an example of a statically typed Groovy script that compiles fine, but results in a type error at runtime. The script is:
int x = "test"
The error received at runtime is:
Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'test' with class 'java.lang.String' to class 'java.lang.Integer' at typesafe.run(typesafe.groovy:1) at typesafe.main(typesafe.groovy)
If Groovy were truly a statically typed language, then the compiler would have raised a compile-time error. But since that did not happen, one or more of the following may be true:
- The Groovy compiler does not perform adequate compile-time typechecking.
- The Groovy compiler performs compile-time typechecking, but a bug prevents it from catching this particular error.
- The semantics of Groovy prevent it from being a statically typed language.
The essence of static typing is that such an error would always be caught at compile time. We can’t say that a language is statically typed if such an error occurs at runtime. Just because the programmer can specify the type of a variable (eg. ‘int’ in this case), it does not mean that the language is statically typed. This is especially true if the compiler or interpreter completely ignores such type specifiers at compile-time.
So in this case, I think the verdict is quite clear: Groovy cannot be considered a statically typed language, as it exhibited a runtime type-related error.
February 19th, 2008 at 4:40 am
Well, actually it is none if the above. It is more a case of there are places (probably accurate to say many places) where the Groovy Compiler defers static checking because Groovy is a dynamic language. There are other places where it chooses to apply static checking. So a language doesn’t have to be purely static or purely dynamic. Just the same as in pre-version 5 Java it is trivial to get a class cast exception. That doesn’t mean the Java isn’t primarily a static language.
February 24th, 2008 at 8:55 am
paulk,
You cannot defer static checking (to runtime).., that’s not static anymore. In Java, it’s trivial to get a NullPointerException too, that doesn’t make Java dynamically typed, just broken.