scala - Using v. Not Using the `self` Type -


given following traits:

scala> trait foo { self =>       |   def f: string = self.getclass.getname      | } defined trait foo  scala> trait bar {       |  def f: string = this.getclass.getname      | } defined trait bar 

and making classes extend them:

scala> class fooimpl extends foo {}  defined class fooimpl  scala> class barimpl extends bar {} defined class barimpl 

and calling f methods on new instances:

scala> (new fooimpl).f res1: string = fooimpl  scala> (new barimpl).f res4: string = barimpl 

the repl shows print out same values - class's name.

perhaps isn't example. what's difference of using self in above foo compared bar, uses this?

in case there's no difference—you're using name this. self types useful when need disambiguate between different thiss. example:

abstract class foo { self =>   def bar: int   def qux = new foo {     def bar = self.bar   } } 

if wrote def bar = this.bar here, compiler complain our definition of bar calling recursively, since this referring anonymous subclass of foo we're defining in qux, not outside foo.


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -