Reputation: 1763
I want to understand why Dart can see that the object b in printBye()
function knows it is an Instance of Bye, but it does not know how to figure out the instance variable a;
class Hello {
void world<T>(T a) {}
}
class Bye {
int a = 1;
}
class Something extends Hello {
@override
void world<T>(T a) {
printBye(a);
}
}
void printBye<T>(T b) {
print(b); // prints Instance of Bye
print(b.a); // error
}
void main() {
new Something()..world(new Bye());
}
https://dartpad.dartlang.org/527e6692846bc018f929db7aea1af583
Edit: here's a simplified version of the code that achieves the same effect:
class Bye {
int a = 1;
}
void printBye<T>(T b) {
print(b); // prints Instance of Bye
print(b.a); // error
}
void main() {
printBye(new Bye());
}
Upvotes: 2
Views: 64
Reputation: 11984
Here's a simple way to look at it: you did call printBye
with a Bye
, but you could have called it with any other type. When you call printBye
with an int
, that int wont have a .a
. Therefore, you have to assume that printBye
could be called with anything. Object
represents that anything as every class derives from it.
If you are sure that it will be called with a Bye
or a subclass, you can do this to get rid of the error:
class Bye {
int a = 1;
}
void printBye<T extends Bye>(T b) {
print(b); // prints Instance of Bye
print(b.a); // not an error anymore
}
void main() {
printBye(new Bye());
}
More info: https://dart.dev/guides/language/language-tour#restricting-the-parameterized-type
Upvotes: 2