14

self 类型类似于以下示例:

trait A { self: String => }

这就是说,那个 trait A(或者它的一个子类型)必须继承 class String

关键字self后跟:一个变量 in 的类比var s: String,类型在后面:

但是=>自我类型中的状态是什么?这背后的原因是什么?

4

3 回答 3

11

Just guess work... You need some specific delimiter of the self-type declaration. Imagine the => was just omitted. this: String would be a syntactically valid statement (although the type checker will complain).

So which should be the delimiter? You wouldn't want nested braces like trait A { self: String { ... }}. So which non-paired existing delimiters exist? => is the only one that I can think of.

Where is => used elsewhere? As sugar for function types (A => B) and for function bodies (i: Int => i + 1). Also for call-by-name arguments, and for the cases of a pattern match. This last usage is somewhat coherent with the self-type. It's like matching this to be of a particular type, and then defining the body depending on this 'match'. I don't know, maybe this is a silly analogy.

于 2012-06-30T22:10:22.813 回答
10

请注意,这self不是关键字,而是普通标识符。你真的可以写任何其他有效的标识符来代替self. :在表达式是类型归属之后,在表达式有效的任何地方都完全有效。

=>就是告诉 Scala 有一个自我类型的原因。否则,self: Type看起来就像一个简单的语句,一个表达式。例如:

class A
class B extends A {
  this: A
}

那是有效的 Scala 代码,它没有 self 类型。

于 2012-07-01T03:44:39.873 回答
0

this是在类体内的范围内,所以从这个意义上说,它是一个参数(尽管我们从来没有这样想过)。自类型语法只是使其明确,并允许给它一个不同的名称(和类型)。所以箭头成为了一个很好的选择,作为活页夹和它的作用域之间的分隔符。

于 2012-07-01T21:52:17.963 回答