Tuesday, April 14, 2009
Groovy has a feature called optional typing which allows types to be declared for fields, parameters and method return values despite Groovy being an otherwise dynamically typed language. This is a useful feature if for no other reason, than for interacting with statically typed languages such as Java. When Java calls Groovy code, it won't have to cast everything to its real type to use it.While the feature itself is useful, the name optional typing, and how the feature is marketed is confusing and misleading. Many assume the phrase optional typing is short for optional static typing1. However, static typing is a term reserved for compile-time type checking2, and Groovy does none of that. This will actually compile (but not run) in Groovy:
int x = "I am not an int!"
I think the term optional typing should be abandoned and the books should be updated to be a little more honest. Programming is difficult enough without having to fight mis-information.
1Groovy In Action specifically states this to be the case, with two pages of text on how to choose between dynamic and static types when writing Groovy programs: "The choice between static and dynamic typing is one of the key benefits of Groovy".
2While wikipedia is never a definitive source, it states nicely that "A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time." It also provides some good references for those who would like a more definitive source of information.
Labels: Optional Typing in Groovy