Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "use strict" for Groovy?

Tags:

groovy

I remember from my Perl days the "use strict" statement that cause the runtime to do extra validations. Is there an equivalent for Groovy?

I do not enjoy being bitten during runtime by what can be detected on compilation, like passing too few arguments to a constructor.

like image 423
ripper234 Avatar asked Oct 21 '10 08:10

ripper234


2 Answers

Groovy 2.0 now has optional static type checking. If you place a @groovy.transform.TypeChecked annotation on a class or method, groovy will use strict, Java-like static typing rules.

In addition, there's another annotation @groovy.transform.CompileStatic that is similar, except it goes a step further and actually compiles it without dynamic typing. The byte code generated for these classes or methods will be very similar to straight Java.

These annotations can be applied to an individual class or method:

 import groovy.transform.TypeChecked

 @TypeChecked
 class MyClass {
      ...
 }

You can also apply them globally to an entire project without adding annotations to the source files with a compiler config script. The config script should look something like this:

withConfig(configuration)  {
    ast(groovy.transform.TypeChecked)
}

Run groovy or groovyc with the -configscript command line option:

groovyc -configscript config.groovy MyClass.groovy

There's more information in the Groovy manual:

  • http://groovy-lang.org/semantics.html#static-type-checking
  • http://groovy-lang.org/semantics.html#_static_compilation
like image 60
ataylor Avatar answered Nov 03 '22 20:11

ataylor


Is there an equivalent for Groovy?

Not that I know of.

I do not enjoy being bitten during runtime by what can be detected on compilation, like passing too few arguments to a constructor.

Then Groovy is probably the wrong language for you and you should use something like Java or C# instead. Alternatively, there is a version of Groovy, known as Groovy++ which has much stronger type-checking, but I don't consider it sufficiently mature for production use.

IntelliJ (and possibly other IDEs) provides a lot of warnings about dodgy Groovy code. Although these warnings don't prevent compilation, they almost give you the best of both worlds, i.e. the safety of a static language and the flexibility of a dynamic language

like image 3
Dónal Avatar answered Nov 03 '22 20:11

Dónal