How to use scala trait with `self` reference?

前端 未结 3 705
天命终不由人
天命终不由人 2020-12-23 16:59

I saw some code write trait as following:

trait SelfAware { self: Self =>
 ....
}

class Self
val s = new Self with SelfAware // this is ok
println(s.self         


        
3条回答
  •  独厮守ぢ
    2020-12-23 17:42

    I also found the answer here: http://markthomas.info/blog/?p=92

    Self Types

    Ordered can be mixed in to any class; it doesn’t depend on any methods or fields of the class that it is mixed in to. Sometimes it’s useful for a trait to be able to use the fields or methods of a class it is mixed in to, this can be done by specifying a self type for the trait. A self type can be specified for a class or a trait as follows:

    trait SpellChecker { self =>
      ...
    }
    

    self within the context of this trait will refer to this. Aliasing this is useful for nested classes or traits where it would otherwise be difficult to access a particular this. The syntax can be extended to specify a lower-bounds on this, when this is done the trait or class can use the features of this lower-bound class, so it can extend or modify its behaviour.

    trait SpellChecker { self: RandomAccessSeq[char] =>
      ...
    }
    

    The compiler will check that any class in a hierarchy including SpellChecker is or extends RandomAccessSeq[char], so SpellChecker can now use the fields or methods of RandomAccessSeq[char]

提交回复
热议问题