self-type `this: T =>` 和 `this: T` 有什么区别?
What's the difference between self-type `this: T =>` and `this: T`?
介于Scala (2.12.8) 之间的自我类型
trait T {
this: Any =>
}
还有这个
trait T {
this: Any
}
语义上有什么区别?
换句话说,this: Any
(在第二个片段中)的目的是什么?
我希望编译器在编译第二个代码片段时大喊我不应该声明 this
,但我却收到了这个警告:
Warning:(2, 9) a pure expression does nothing in statement position
multiline expressions may require enclosing parentheses
this: Any
关键字 this
是类型 T
的表达式。 T
是 Any
的子类型,因为一切都是 Any
的子类型。因此你可以 explicitly ascribe type Any
到表达式 this
。初始化器中有表达式是有效的,所以你可以在 T
.
的主体中写表达式 this: Any
你还不如写
trait T { 42: Int }
或
trait T { ((((this: T): T): T): T): Any }
在这两种情况下,42
和 this
只是具有显式类型归属的表达式,根本不执行任何操作。它们不是声明,与 self 类型无关。
介于Scala (2.12.8) 之间的自我类型
trait T {
this: Any =>
}
还有这个
trait T {
this: Any
}
语义上有什么区别?
换句话说,this: Any
(在第二个片段中)的目的是什么?
我希望编译器在编译第二个代码片段时大喊我不应该声明 this
,但我却收到了这个警告:
Warning:(2, 9) a pure expression does nothing in statement position
multiline expressions may require enclosing parentheses
this: Any
关键字 this
是类型 T
的表达式。 T
是 Any
的子类型,因为一切都是 Any
的子类型。因此你可以 explicitly ascribe type Any
到表达式 this
。初始化器中有表达式是有效的,所以你可以在 T
.
this: Any
你还不如写
trait T { 42: Int }
或
trait T { ((((this: T): T): T): T): Any }
在这两种情况下,42
和 this
只是具有显式类型归属的表达式,根本不执行任何操作。它们不是声明,与 self 类型无关。