在另一个方法中访问Scala Trait方法

时间:2016-10-23 12:52:38

标签: scala

我正在写一个包含函数的特征:

trait MyTrait[X,Y] {
  def f(x : X) : Y
}

我试图添加地图功能:

trait MyTrait[X,Y] {
  def f(x : X) : Y // the outer f

  def map[Z](g : Y => Z) : MyTrait[X,Y] = MyTrait[X,Z] {
    //namespace conflict : I need to access the outer f within this f
    override def f(x : X) : Z = outerF andThen g  
  }
}

我的问题是:我如何引用外部f我已尝试super.fthis.f无济于事。我确定这是以前提出过的一个基本问题,但它并不是非常可靠的#34;容易搜索。

提前感谢您的考虑和回应。

2 个答案:

答案 0 :(得分:2)

您可以使用self类型

trait MyTrait[X,Y] {
  self => 
  def f(x : X) : Y // the outer f

  def map[Z](g : Y => Z) : MyTrait[X,Y] = MyTrait[X,Z] {
    override def f(x : X) : Z = self.f andThen g  
  }
}

答案 1 :(得分:1)

您也可以使用override def f(x : X) : Z = MyTrait.this.f andThen g

相关问题