1

I ran into the following problem:

class A {}

class B extends A {}

class C<T extends A> {
  C() {
    test(B()); // line 7
  }
  
  void test(T t) {}
}

Error: The argument type 'B' can't be assigned to the parameter type 'T' - line 7

I don't understand why type B can't be assigned to a parameter of type T because B clearly extends A and T is also defined to extend A? To fix this error I tried casting B to B:

test(B() as B);

Info: Unnecessary cast - line 7

The info makes sense to me but I don't understand why this cast fixes the error and this also works at runtime for me. The best solution without any errors or info I found was:

test(B() as T);
1
  • Copying and pasting your code into DartPad, test(B() as B) does not remove the assignment error for me. I instead get the warning about the unnecessary cast and the assignment error, which seems correct.
    – jamesdlin
    Jan 7, 2021 at 10:12

1 Answer 1

2

I don't know Dart, but this wouldn't be valid in C# either, and I'd expect the reason to be the same.

Suppose you had this code (apologies for any invalid syntax):

class D extends A {}

var c = C<D>();

Within the context of that new object, the relevant T is D - it's an instance of C<D>. So your test method logically expects a D... but you're providing it a B. Suppose your test method stored that value, and then another method returned it later as a T - then you could have:

var c = C<D>();
var d = c.getValue();

That code would expect the return value of getValue() to be a D, but it would actually be a B.

I don't know enough about Dart to know why the cast removes the error, but it looks to me like your code is fundamentally dangerous and could fail at some point in the kind of scenario I described above. I suspect you need to redesign the code.

4
  • Thanks, this makes sense now. But personally I think it’s still weird that casting B to B fixes the error.
    – LeFrosch
    Jan 7, 2021 at 9:51
  • @LeFrosch: Yes, I think that part is odd too. It wouldn't help in C# for example.
    – Jon Skeet
    Jan 7, 2021 at 10:05
  • I think you meant "but you're providing it a B". I'd edit your post to correct it, but editing a post by Jon Skeet somehow feels wrong...
    – jamesdlin
    Jan 7, 2021 at 10:09
  • @jamesdlin: Oh always feel free to correct it if you're confident - and you were absolutely right. Fixed now, thanks
    – Jon Skeet
    Jan 7, 2021 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.