0

I have this function:

double discount() {
    return cost_min_discounted != null ? cost_min - cost_min_discounted : 0;
}

cost_min_discounted is defined as double?
I get the error:

The argument type 'double?' can't be assigned to the parameter type 'num'

What's the best way to write code like that? I check for the null value, so the code seems correct to me.

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
Giacomo M
  • 4,450
  • 7
  • 28
  • 57

1 Answers1

1

While you've already checking null at beginning, use ! at the end.

double discount() {
  return cost_min_discounted != null ? cost_min - cost_min_discounted! : 0;
}
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • 1
    Since it is a class field it can theoretically change between your check and the usage. In a multithreaded application this can be a really hard bug to track down. Assigning to a local variable first guarantees it will never be null when used. – Dan Harms May 28 '22 at 14:50
  • What about `return cost_min - (cost_min_discounted ?? 0)` – Giacomo M May 28 '22 at 15:13
  • @DanHarms as it already checked the null value, I can't see any possibility to get it null and throw the error, It will return the right expression on null cases. – Md. Yeasin Sheikh May 28 '22 at 15:44
  • @GiacomoM yes it will return `cost_min` if `cost_min_discounted` becomes null. – Md. Yeasin Sheikh May 28 '22 at 15:46
  • Another thread can change the value. There's a reason you have to add the bang to the use because it's not guaranteed non-null there. – Dan Harms May 28 '22 at 16:26