我正在学习抽象类,这个链接非常有用
scala generic method overriding
abstract class Foo[T] { self:T =>
def bar1(f:T):Boolean
def bar2(f:T):T
}
class FooImpl extends Foo[FooImpl]{
override def bar1(f:FooImpl) = true
override def bar2(f:FooImpl) = f
}
self:T 代表什么?据我所知,T 是类参数。
最佳答案
正如@cchantep 在他的评论中提到的,self : T
在这种情况下是 自类型注解 基本上是说 Foo[T]
的一个实例还需要表现得像 T
.你可以在 FooImpl
中看到确实如此。 ,如 FooImpl <: Foo
.
你可以找到更多关于自我类型注释 here , here或 here .请注意,大多数情况下,您会看到它在依赖注入(inject)和蛋糕模式的上下文中使用。
最有趣的来自 the second link我认为最初的部分是:
In other words, what is the point of doing this:
trait A
trait B { this: A => }
when you could instead just do this:
trait A
trait B extends A
Why should you use [this syntax]?
[...] the answer generally comes down to "B requiring A" (annotations) vs "B being an A" (inheritance) and that the former is better for dependency management.
最后,为了澄清,请注意
self
这个词根本没有必要。这可以是任何有效的变量名,但 self
或 this
大部分时间都是一个约定。也就是说,您可以这样做:trait A
trait B { myVar: A => }
但这不太常见。
关于Scala抽象类,self做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41858604/