1

The code below produces a type error of:

"The argument type int can't be assigned to the parameter type num"

Why is sum being considered a num, when it's defined as int?

If I change sum from int to var, the error disappears.

Can someone explain why this is happening?

abstract class ISomeInterface {
  void add<T>(T x);
}

class SomeClass implements ISomeInterface {
  int sum;

  @override
  void add<int>(int x) {
    sum = sum + x;
  }
}
Baker
  • 24,730
  • 11
  • 100
  • 106
  • Do you want your subclass to be specialized for a single type? If you move the generic from the method level to class level it will compile. – gugge May 11 '20 at 19:30
  • @gugge Yes the idea was the method could handle `int` or `double`. If I removed the generic type specification on `add()` no type checking error surfaced. But, I'm wondering why this is happening (I assume I'm not understanding some rule/concept of Dart). – Baker May 11 '20 at 19:37
  • Hm I guess it is confusing for the compiler since there is typed dependencies outside of the method (sum). If you want to handle both int and double you could make it class level generic with `Someclass implements ISomeInterface` and sum of type `T`. – gugge May 11 '20 at 20:27
  • 1
    Maybe you can find some answers here: https://dart.dev/guides/language/sound-problems#invalid-method-override and https://stackoverflow.com/questions/61022367/dart-doesnt-override-generic-method-has-generic-parameter-type-similar-to-the – gugge May 11 '20 at 20:28
  • 1
    Ah, I think you hit it. I'm tightening the scope of a param type in a subclass, which isn't allowed. Thanks @gugge! – Baker May 11 '20 at 21:17

0 Answers0