Originally posted by Marc Peabody:
The fact that Groovy lets you choose static or dynamic is pretty cool. I do Here's his blog post on the topic.
Groovy does not let you choose between static or dynamic typing. Groovy has a very few static semantic constraint checks, but it's pretty much a dynamically typed language. When you add type annotations in Groovy what you get is an automatic runtime check that a value has a certain runtime type. That's different from a static type system that proves a value will always have a certain type. That's not to knock Groovy's choice in this matter, it's just to point out the difference. Here's an example.
I create a function that promises an int but returns a String.
groovy:000> def int foo() { return "hello";}
===> true
Groovy accepts it no problem
But then I try to run it and...
groovy:000> foo()
ERROR org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'hello' with class 'java.lang.String' to class 'java.lang.Integer'
at groovysh_evaluate.foo (groovysh_evaluate:2)
at groovysh_evaluate.run (groovysh_evaluate:2)
Now I get the error
Here's the equivalent in Scala. It complains at definition time
scala> def foo : Int = "hello"
<console>:4: error: type mismatch;
found : java.lang.String("hello")
required: Int
def foo : Int = "hello"