简体   繁体   中英

How to access declared script fields from within classes in Groovy?

Let's say I have the next groovy code snippet:

def weightArg = args[0]

class Box {

   def width

   def height  

   def double weight() {
       //I want to return the value of weightArg here. How can I do that? 
   }
}

I want to let my class Box use some variables from its environment. What's the correct way to do it?

It seems that weightArg should be static and I should be able to get it from Box static initializer, but I cannot manage to overcome the compiler.

Declaring a class in a middle of a script and making it dependent on scripts local variables is a definite sign of a bad design. If you can't design this whole system in OO way than stick to procedural programming. The main purpose of writing OO programs is factoring them to little independent pieces. In your case it's neither factoring, nor independent, and I'm pretty sure it has no purpose you could express in words.

In other words either don't declare a Box type at all or do it similar to this way:

class Box {
  Box(weight) { this.weight = weight }
  def width, height, weight
}

And use it like this:

def box = new Box(args[0])

Thus you get it abstracted from weightArg and args[0] and also become able to reuse it in different scenarios.

Otherwise you foredoom your program to be unmanageable and therefore dead after first revision. In decades of existence of OO programming it's been pretty much proven.

Another thing to note is that when you get a feeling that you need to introduce classes in your script it is a reliable sign that your program should be written as a normal application with packages and stuff - not as a script.

Regardless of whether it's "right" to do so or not, the way that you can access your weight variable from within the Box class is to simply remove the word "def". The reason why is described here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM