I would like to create a class and refer to the "type of the current class".
So for example in this small snippet, I create a class A
which has .child
.
As it is written, the type of .child
(A?
) is "hardcoded", what I mean is, if I create B
that extends A
, .child
will be of type A?
. I would like it to automatically be B?
"because the current class is B
".
class A {
A? child;
}
class B extends A {
}
B? f(B b) {
return b.child;
}
As it is right now, it shows the error
line 10 • A value of type 'A?' can't be returned from the function 'f' because it has a return type of 'B?'.
Is there a way to do what I am trying to do? If yes, how?
One approach would be to use generics and borrow the curiously-recurring template pattern from C++ so that the base class knows the derived class's type:
class A<Derived extends A<Derived>> {
Derived? child;
}
class B extends A<B> {
}
Alternatively you could make A
an abstract class and have B
override child
:
abstract class A {
A? get child;
}
class B extends A {
@override
B? child;
}
If A
needs a setter for child
, you can use covariant
to appease static analysis and allow the setter's value to be checked at runtime:
abstract class A {
A? get child;
set child(A? value);
}
class B extends A {
@override
covariant B? child;
}