Re: [Vala] Understanding object creation (and other things)



On Son, 2007-04-22 at 11:55 +0100, Phil Housley wrote:
You can do this with construct-only properties without storing the value
anywhere.
...
The construct in the parameter of the creation method is just a short
version of setting the property x to the value of the argument x.

Ok, I think I'm getting some of this.  To add a little complexity
though, say I want to do something like a multiplier that stores the
answer and not the terms.  This means I need two construct parameters
to set one value:

class Mul {
      private int answer;

      public int get_answer() {
              return answer;
      }

      public void set_terms(int x, int y) {
              answer = x * y;
      }

      public Mul(int x, int y) {
              set_terms(x, y)
      }
}

The closest I can get in vala seems to be:

[...]
      
But that keeps the original x and y around for ever, even when the
terms have been changed.  And is a lot of work also.

Is there a way of cutting this back now, or is the syntax likely to
shrink in the future maybe?

The only sensible possibility to make this simpler would be to allow
accessing the construction parameters in the constructor, maybe
something like that:

class Mul {
        private int answer;

        public int get_answer() {
                return answer;
        }

        public void set_terms(int x, int y) {
                answer = x * y;
        }

        public Mul(construct int x, construct int y) {
        }

        // implicitly declare construct-only parameters x and y
        // with a default value of -1
        construct (int x = -1, int y = -1) {
                set_terms(x, y)
        }
}

Would something like that make sense?

The way I'd implement such a class currently is by using a helper method
for construction - assuming that you don't want to create instances of
subtypes in the same manner.

class Mul {
        private int answer;

        public int get_answer() {
                return answer;
        }

        public void set_terms(int x, int y) {
                answer = x * y;
        }

        public static Mul! create_with_terms (int x, int y) {
                var mul = new Mul ();
                mul.set_terms (x, y);
                return mul;
        }
}

Jürg




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]