Using this keyword to inherit? [duplicate]

天大地大妈咪最大 提交于 2019-12-23 09:49:42

问题


Possible Duplicate:
What is the difference between scala self-types and trait subclasses?

From example in scalatest site. There is one particular thing I don't really understand

trait FunSuiteStackBehaviors { 
                   this: FunSuite => //This line
                         def a() {}
                         def b() {}
}

class StackFunSuite extends FunSuite with FunSuiteStackBehaviors {}

As far as I understand, it seems like they try to assign some defs into a trait. But what does this: FunSuite => part do ? I tried to use extends FunSuite instead like

trait FunSuiteStackBehaviors extends FunSuite { 
                         def a() {}
                         def b() {}
}

class StackFunSuite extends FunSuite with FunSuiteStackBehaviors {}

and I still end up with same result. Are they the same thing ?


回答1:


the this: => XXXX is called a self type annotation http://www.scala-lang.org/node/124 Basically, you're specifying the type of "this" (current object) to the type specified. Kind of a "cast from the inside"




回答2:


this: FunSuite => is called self type annotation. There is nothing special about "this" Both snippets are equivalent. Here is some discussion on its rationale. In short self type annotation helps to signify compositional nature rather than IS-A relation.



来源:https://stackoverflow.com/questions/8371448/using-this-keyword-to-inherit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!