开发者

Is there a "use strict" for 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.


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


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


No, there is no such thing, and there can't be. Perl's "use strict" only prevents the use of undeclared variables (and some very Perl-specific things that I don't think have equivalents in Groovy).

In dynamic languages like Groovy, "passing too few arguments to a constructor" is fundamentally not something the compiler can detect, because class definitions can be changed at runtime via metaprogramming. Also, you usually don't have the type information necessary to know what class to look at.

If you want maximum compile-time checks, use a statically typed language with no metaprogramming, i.e. Java.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜