How to use scala trait with `self` reference?

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

    To answer the other half of your question (why does println(s.self) produce an error?), that is because self is not a field of SelfAware. It can be used to define such fields, however:

    trait SelfAware { self =>
      val me = self
    }
    
    class X
    val x = new X with SelfAware
    println(s.me)
    

提交回复
热议问题