对象自注释是什么意思?

时间:2012-06-28 10:24:21

标签: scala mixins self-type

  

可能重复:
  What is the difference between scala self-types and trait subclasses?

我理解一个自我注释作为对编译器的承诺,程序员在其中表明特征将与带注释的特征混合。例如:

scala> trait X
defined trait X

scala> trait Y { this: X => }
defined trait Y

scala> new Y {}
<console>:10: error: illegal inheritance;
self-type Y does not conform to Y's selftype Y with X
              new Y {}
                  ^

scala> new Y with X {}
res1: Y with X = $anon$1@1125a40

在前面的示例中,第三个表达式失败,因为我们没有为新实例设置有效的X.显然,最后一个很好用。到现在为止还挺好。现在,让我们看另一个涉及对象的例子。

scala> object Z { this: X => }
defined module Z

我理解对象是在实例化时失败的X承诺(我们现在正在创建一个具有未来承诺的实例!),如下一行所示,其中特征已被略微修改:

scala> trait X { class X1 }
defined trait X

scala> trait Y { this: X => new X1 }
defined trait Y

scala> object Z { this: X => new X1 }
<console>:8: error: not found: type X1
       object Z { this: X => new X1 }
                                 ^

那么,对象自我注释意味着什么?

1 个答案:

答案 0 :(得分:3)

事实上,你可以对类做同样的事情 - 添加一个不被继承的自我类型,但你将无法实例化这样的类。

允许单例对象具有自身类型不会以任何方式使程序无效 - 您将无法从单例对象中调用自我类型的任何方法(或实例化其内部类),因为它没有继承自我类型。

然而,它可能是一个错误,您可能希望file a bug

相关问题