编译器似乎忽略了类型细化中的类型绑定

时间:2015-08-13 01:46:02

标签: scala type-inference path-dependent-type type-bounds

以下代码中的类型细化似乎表明路径相关类型Object包含vt.ValueT

this.type

但Scala编译器(版本2.11.2)说:

trait ValueType {
  type ValueT <: Value

  type ConstrainedT <: ConstrainedValue

  def makeConstrainedValue(v: ValueT): ConstrainedT = ???
}

trait Value {
  type ValueTypeT <: ValueType { type ValueT >: this.type } // <--- HEY, COMPILER, READ THIS

  val vt: ValueTypeT

  def asConstrainedValue = vt.makeConstrainedValue(this) // <--- Compiler complains here
}

trait ConstrainedValue { /* details omitted */ }

为什么推断error: type mismatch; found : Value.this.type (with underlying type Test.Value) required: Value.this.vt.ValueT override def asConstrainedValue = vt.makeConstrainedValue(this) ^ 在这里是非法的?还有另一种方法可以告诉编译器它需要知道什么吗?

我尝试将类型细化放在this.type <: vt.ValueT的声明上。结果类型为volatile的编译器对象。也许这就是问题的线索。

细化vt会生成相同的错误消息。

1 个答案:

答案 0 :(得分:5)

我认为问题是在绑定this中,override的绑定在某种程度上被编译器弄糊涂了。如果我进行了以下更改(并从asConstrainedValue删除trait Value { self => type ValueTypeT <: ValueType { type ValueT >: self.type } … ),则编译成功对我来说:

#include <iostream>

class Point2d {
public:
    double x;
    double y;
    Point2d() : x(0), y(0) {
    }
    Point2d(double x, double y) : x(x), y(y) {
    }
    void Show() {
        std::cout << "(" << x << "," << y << ")\n";
    }
};

class Vector2d : public Point2d {
public:
    Vector2d():Point2d(){
    }
    Vector2d(double x, double y) : Point2d(x,y) {       
    }
    Vector2d(Vector2d const& vec) : Point2d(vec){
    } 
    void Set(double x, double y) {
        Point2d::Point2d(x, y);
    }
};

int main() {
    Vector2d v;
    v.Set(20, -39);
    v.Show(); // prints '(0,0)' instead of '(20,-39)'
}