Static Type Checking in Groovy 2.0

25 / Sep / 2012 by Mohit Garg 0 comments

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:

  1. To check the return type of any method
  2. Assignment type checking
  3. Method missing
  4. 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

FOUND THIS USEFUL? SHARE IT

Tag -

Groovy

Leave a Reply

Your email address will not be published. Required fields are marked *