Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
titleGreet.groovy

class Greet {
  def salute( person ) { println "Hello ${person.name}!" }
  def welcome( Place location ) { println "Welcome to ${location.state}!" }
}

g = new Greet()
g.salude()                //misspelling
g.welcome( 123 )          //wrong argument type

 

Note that running groovyc Greet.groovy does not produce any errors. Instead, a MissingMethodException is thrown at runtime.

This is because Groovy is a dynamic language. Several other things could be happening to make this code valid at runtime. Using the MetaClass, you could add a salude() method to the Greet class at runtime. You could also add a state property to Number, which would make the welcome(..) call valid. See ExpandoMetaClass and TMPGroovy Categories.

Type checking to the rescue

If all you need is a scripting language and that you don't rely on the dynamic behaviour, since Groovy 2.0.0, you can add an annotation that will activate type checking:

Code Block
titleGreet.groovy
@groovy.transform.TypeChecked
class Greet {
  def salute( person ) { println "Hello ${person.name}!" }
  def welcome( Place location ) { println "Welcome to ${location.state}!" }
}

The compiler will report errors at compile time instead of runtime. See GEP 8 - Static type checking for details.

Will I get a performance boost if I statically type all of my fields and methods?

...

Can't we provide some sort of "NotDynamic" flag to speed up method invocation?

This has been discussed on the mailing list many times before. Although it has not been ruled out entirely, there are many implications to such a 'feature'. The primary focus right now is to improve the performance of normal, dynamic Groovy. Groovy is already performant enough for "most" use cases. If you see a performance bottleneck in your code, the typical optimization path is to factor out those pieces to Java code, and call them from Groovy. See this thread and this oneSince Groovy 2.0.0, you can annotate your code with @CompileStatic. Be warned that while this will improve performance, it changes the semantics of your code. See GEP 10 - Static compilation for details.