开发者

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

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?


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.


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.


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
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜