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

14,674

Solution 1

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.

Solution 2

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.

Solution 3

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
}
Share:
14,674

Related videos on Youtube

Ant's
Author by

Ant's

Updated on May 25, 2022

Comments

  • Ant's
    Ant's almost 2 years

    I read use keyword in Groovy. But could not come out with, for what it has been exactly been used. And i also come with category classes, under this topic,what is that too? And from, Groovy In Action

    class StringCalculationCategory {
      static def plus(String self, String operand) {
        try {
          return self.toInteger() + operand.toInteger()
        } catch (NumberFormatException fallback) {
          return (self << operand).toString()
        }
      }
    }
    
    use (StringCalculationCategory) {
      assert 1 == '1' + '0'
      assert 2 == '1' + '1'
      assert 'x1' == 'x' + '1'
    }
    

    With the above code, can anyone say what is the use of use keyword in groovy? And also what the above code does?

    • Ant's
      Ant's almost 12 years
      @simon: its an excellent book you can find!
    • Bill K
      Bill K
      @niccolom. I've been using it along with Java for about 5 years now, I'd say it was worth it for certain types of code. Java is good for team development, Groovy is better for fast scripting and flexible approaches to problem solving. Most of the time it's a wash but the occasional use of StringBuilder or helpers like File.text make it VERY worth while for scripts, prototypes and tests.