Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

Weird dart generic assignment behaviour

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...