What is the difference between self-types and trait subclasses?

后端 未结 11 2093
名媛妹妹
名媛妹妹 2020-11-22 08:53

A self-type for a trait A:

trait B
trait A { this: B => }

says that \"A cannot be mixed into a concrete cl

11条回答
  •  醉梦人生
    2020-11-22 09:33

    Self types allow you to define cyclical dependencies. For example, you can achieve this:

    trait A { self: B => }
    trait B { self: A => }
    

    Inheritance using extends does not allow that. Try:

    trait A extends B
    trait B extends A
    error:  illegal cyclic reference involving trait A
    

    In the Odersky book, look at section 33.5 (Creating spreadsheet UI chapter) where it mentions:

    In the spreadsheet example, class Model inherits from Evaluator and thus gains access to its evaluation method. To go the other way, class Evaluator defines its self type to be Model, like this:

    package org.stairwaybook.scells
    trait Evaluator { this: Model => ...
    

    Hope this helps.

提交回复
热议问题