Reputation: 198198
Dart code:
main() {
var child1 = new Child1();
var t = child1.childType();
}
class Parent {
??? childType() {
return this.runtimeType;
}
}
class Child1 extends Parent {
}
class Child2 extends Parent {
}
You can see the ???
in class Parent
, I want it to reference to child's type, but I don' know how to declare it.
In scala, it can be:
def childType(): this.type = {
...
}
But I don't know how to do it in dart. Is it possible? If not possible, what's the best type to use here?
Upvotes: 1
Views: 157
Reputation: 11171
If you really need the return type of childType
to statically be declared as the right subtype, you can use generics:
class Parent<C extends Parent> {
C get childType => runtimeType;
}
class Child1 extends Parent<Child1> {}
class Child2 extends Parent<Child2> {}
I'd really make sure you need that though. You could just keep childType
typed as Parent
.
Upvotes: 3