What is the use of "use" keyword/method in groovy?

A very good illustration is groovy.time.TimeCategory. When used together with use() it allows for a very clean and readable date/time declarations.

Example:

use (TimeCategory) {
    final now = new Date()
    final threeMonthsAgo = now - 3.months
    final nextWeek = now + 1.week
}

use is useful if you have a class you don't have the source code for (eg in a library) and you want to add new methods to that class.

By the way, this post in Dustin Marx's blog Inspired by Actual Events states:

The use "keyword" is actually NOT a keyword, but is a method on Groovy's GDK extension of the Object class and is provided via Object.use(Category, Closure). There are numerous other methods provided on the Groovy GDK Object that provide convenient access to functionality and might appear like language keywords or functions because they don't need an object's name to proceed them. I tend not to use variables in my Groovy scripts with these names (such as is, println, and sleep) to avoid potential readability issues.

There are other similar "keywords" that are actually methods of the Object class, such as with. The Groovy JDK documentation has a list of such methods.


See the Pimp My Library Pattern for what use does.

In your case it overloads the String.add(something) operator. If both Strings can be used as integers (toInteger() doesn't throw an exception), it returns the sum of those two numbers, otherwise it returns the concatenation of the Strings.

Tags:

Groovy