How to use scala trait with `self` reference?

前端 未结 3 711
天命终不由人
天命终不由人 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:57

    The error is occurring because you have constrained the type of the this reference (which you have named self) to be of type Self. When you say new Self with SelfAware, this is OK, because that object is of type Self like you asked. But when you say new X with SelfAware, there is no evidence that X is in any way a subtype of Self.

    In your new object of type X with SelfAware, what would be the type of its self member? Well, it would not be of type Self, but of type X. But you have defined the trait SelfAware so that self must be of type Self, so you get a type error.

提交回复
热议问题