Static Type Checking in Groovy 2.0
Groovy is a dynamic language. We can’t check any typo error, method or property missing error at compile time. To check typo error, method or property missing at compile time, Groovy 2.0 introduces new features named as Static Type Checking which helps to check errors at compile time.
To use static type checker in groovy
You have to write @TypeChecked annotation above the method. It enables method to check errors at compile time.
[groovy]
import groovy.transform.TypeChecked
void findData() {}
@TypeChecked
int testData() {
// compilation error:
// cannot find matching method findssssData()
findssssData()
def name = "Hello"
// compilation error:
// the variable naaammme is undeclared
println naaammme
// compilation error
// cannot return string value if method return type is integer
return "hello"
}
[/groovy]
This code will give the errors at compile time for method missing (findssssData), variable missing (variable name) and invalid return type.
You can use static type checking in following case:
- To check the return type of any method
- Assignment type checking
- Method missing
- Variable missing
To know more about static type checking, you can use following links:-
http://www.infoq.com/articles/new-groovy-20
http://www.infoq.com/news/2011/11/groovy-updates