0

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!

Phoebe
  • 1
  • 1
  • This code, as is, would crash with a `NullPointerException` during initialization of `c` because `a` would be null. Maybe your actual code is different? – ernest_k Apr 07 '22 at 15:00
  • In actual code, only difference is that - the field datatype is Boolean instead of Integer – Phoebe Apr 07 '22 at 15:04
  • i can't understand why it should be `9` when `(4 > 5) ? 4+5 : 4+10` returns 14 for `a=4` – daggett Apr 07 '22 at 15:09
  • Typo :P Corrected condition, thanks! – Phoebe Apr 07 '22 at 15:11
  • "In actual code, only difference is that - the field datatype is Boolean instead of Integer" - Is there some reason that you asked for a solution for `Integer` instead of `Boolean`? – Jeff Scott Brown Apr 07 '22 at 16:12

2 Answers2

1

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

tim_yates
  • 167,322
  • 27
  • 342
  • 338
0
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()
daggett
  • 26,404
  • 3
  • 40
  • 56
  • FYI... The requirements in the question are not entirely clear but the attempt made in the code included in the question suggests that `c` should only be assigned a value once. The way the code in this answer is written, the value of `c` can change over time. Specifically, it would change if `a` or `b` was ever changed. That might or might not be the intent. – Jeff Scott Brown Apr 07 '22 at 15:58
  • i got the requirements this way )) `without explicitly setting value for c`. – daggett Apr 07 '22 at 16:16
  • 1
    Right. I understood the without explicitly setting value for `c` part. What I am pointing out is that the value of `c` will change when the value of `a` or `b` changes, even without explicitly setting a value for `c`. That may indeed be the intent, I am not saying it is a mistake. I am just pointing out that it is inconsistent with 1 way to read the intent that could be read in the original code. – Jeff Scott Brown Apr 07 '22 at 16:25