Ramon J Romero y Vigil Ramon J Romero y Vigil - 1 month ago 7
Scala Question

Accessing a Scala Trait method inside another method

I am writing a trait that contains a function:

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


I'm trying to add a map function:

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
}
}


My question is: how do I reference the outer
f
?
I've tried
super.f
and
this.f
to no avail. I'm sure this is a basic question that has been asked before but it's not very "google-able", e.g. easy to search for.

thank you in advance for your consideration and response.

Answer

You can use self type

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  
  }
}
Comments