Hi folks, can someone please tell me why the follo...
# announcements
a
Hi folks, can someone please tell me why the following isn't possible?
Copy code
object MoonWidgetInput
object MoonWidgetOutput
object MoonWidgetData

abstract class BaseVehicle<INPUT, OUTPUT>

abstract class BaseWidget<INPUT, DATA, OUTPUT>() {
    abstract var vehicle : BaseVehicle<INPUT, OUTPUT>
}

class MoonRover : BaseVehicle<MoonWidgetInput, MoonWidgetOutput>()

class MoonWidget : 
    BaseWidget<MoonWidgetInput, MoonWidgetData, MoonWidgetOutput>(){
    override var vehicle = MoonRover()
}
The
vehicle
override in
MoonWidget
is telling me that
MoonRover
is not a type of overriden
BaseVehicle<MoonWidgetInput, MoonWidgetOutput>
e
generic types are invariant by default
I presume you intended
Copy code
abstract class BaseVehicle<in INPUT, out OUTPUT>
abstract class BaseWidget<in INPUT, DATA, out OUTPUT>
or something along those lines
invariant:
<Base>
and
<Derived>
are unrelated. example: neither
MutableList<Base>
nor MutableList<Derived>` can be used in the place of the other
covariant:
<Derived>
can be used in place of
<Base>
. example:
List<Derived>
can be used in place of
List<Base>
contravariant:
<Base>
can be used in place of
<Derived>
. example:
(Base) -> Unit
can be used in place of
(Derived) -> Unit
a
thanks! Hmm ok I see the problem but not so clearly the fix. Since my base is the parameterized
BaseWidget<X,Y,Z>
and derrived is a class extending that, it's THAT relationship that'd have to be covariant right?
e
if you only declare
BaseVehicle<in INPUT, out OUTPUT>
it should work
a
I seem to get the same error with this change. As a workaround I could have an abstract setter function instead but I think it'd be cleaner with a property
variance always confuses the hell out of me for some reason 😕
e
works with an explicit type
Copy code
override var vehicle: BaseVehicle<MoonWidgetInput, MoonWidgetOutput> = MoonRover()
var
has to be invariant and without the type it's inferring it from
MoonRover
a
Got it! Thanks so much for the detail on explanation. Appreciate it