2

我正在尝试实现类DistanceCMDistanceMM,并且我希望它们可以互换地求和,只要它们都继承自Distance.

但是,我收到此错误:

“错误:(46、76)锡兰:声明'Summable'的类型参数'Other'有参数'Distance',它不能分配给'Other'的上限'Summable'”

...我无法破译...错误消息指的是下面代码中的这一行:

shared actual Distance plus(Distance other) 

这是当前代码:

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
}
4

1 回答 1

2
interface Summable<Other> of Other​ given Other satisfies Summable<Other>

注意约束(given子句)。您声称DistanceMM满足Summable<Distance>,但不满足(不满足)Distance的约束。尝试这个:OtherDistanceSummable<Distance>

interface Distance of Centimeter | Millimeter satisfies Summable<Distance> {}

class Centimeter() satisfies Distance {
    shared actual Distance plus(Distance other) => nothing;
}

class Millimeter() satisfies Distance {
    shared actual Distance plus(Distance other) => nothing;
}
于 2017-08-29T17:42:26.103 回答