Groovy: Class fields default conditional values

123 views Asked by At

I have below sample classes in my application:

class A {
   Integer a
   String b
   Integer c = (a < 5) ? a+5 : a+10
}

class B {
   void method1() {
      A a = new A(a:4, b:"test")
      log.print("c: ", a.c)
   }
}

When my code is calling method1, then it outputs c = 14. but ideally it should 9.

How we can solve this without explicitly setting value for c? Thanks in advance!

2

There are 2 answers

3
daggett On
class A {
   Integer a
   String b
   def getC(){ (a < 5) ? a+5 : a+10 }
}

class B {
   def method1() {
      A a = new A(a:4, b:"test")
      println("c: " + a.c)
   }
}

new B().method1()
0
tim_yates On

Not 100% sure of the question, and the example won't print anything as it will fail to add 5 to null, but an alternative might be to use the @Lazy annotation to defer creation of the value until such time as it is requested, ie:

class A {
   Integer a
   String b
   @Lazy Integer c = { (a < 5) ? a+5 : a+10 }()
}

After it has been requested, it will keep this value, no matter how you change a and b (unless you change c yourself). From the question, I have no idea if this is what you want or not