I'm trying to implement classes DistanceCM
and DistanceMM
, and I want these to be summable interchangeably, as long as they both inherit from Distance
.
However, I get this error:
"Error:(46, 76) ceylon: type parameter 'Other' of declaration 'Summable' has argument 'Distance' which is not assignable to upper bound 'Summable' of 'Other'"
...which I can't decipher... The error message refers to this line in the code below:
shared actual Distance plus(Distance other)
This is the current code:
abstract class Distance() of DistanceMM | DistanceCM {
shared formal Distance multiplyScalar(Float scalar);
}
class DistanceMM(variable Float val) extends Distance() satisfies Summable<Distance>
{
shared Float distanceInMillimeters;
shared Float distanceInCentimeters;
switch (unit)
case (millimeter) {
distanceInMillimeters => val;
distanceInCentimeters => val / 10;
}
case (centimeter) {
distanceInMillimeters => val * 10;
distanceInCentimeters => val;
}
shared actual DistanceMM multiplyScalar(Float scalar) {
val = val * scalar;
return this;
}
shared actual Distance plus(Distance other) {
switch (other)
case (DistanceMM) {
return DistanceMM(val + other.distanceInMillimeters(), unit);
}
case (DistanceCM) {
return DistanceMM(val + other.distanceInCentimeters(), unit);
}
}
}
class DistanceCM(variable Float val) extends Distance() satisfies Summable<Distance>
{
shared Float distanceInMillimeters;
shared Float distanceInCentimeters;
switch (unit)
case (millimeter) {
distanceInMillimeters => val;
distanceInCentimeters => val / 10;
}
case (centimeter) {
distanceInMillimeters => val * 10;
distanceInCentimeters => val;
}
shared actual DistanceCM multiplyScalar(Float scalar) {
val = val * scalar;
return this;
}
// implementation missing
}
Notice the constraint (the
given
clause). You're claiming thatDistanceMM
satisfiesSummable<Distance>
, butDistance
doesn't satisfy the constraint onOther
(Distance
doesn't satisfySummable<Distance>
). Try this: