csvan
csvan

Reputation: 9454

Function inheritance - call method in super class on child.apply()

Suppose I have the following:

abstract class ParentFunction extends Function[String, String] {
  def useful: Any = // do something useful, such as notifying a listener
}

class ChildFunction extends ParentFunction {
  override def apply(arg: String): String = "Did something special, and something generally useful!"
}

Is there any way, apart from explicitly invoking 'useful', that I can make sure that 'useful' is implicitly called whenever ChildFunction (or any other descendant of ParentFunction is called?

Upvotes: 0

Views: 143

Answers (2)

Sean Vieira
Sean Vieira

Reputation: 159915

The simplest way is to simply not have the children provide apply but some other method:

abstract class ParentFunction extends Function[String, String] {
  def useful: Any = println("Doing useful work")
  def doWork(arg: String): String
  override final def apply(arg: String): String = {
    useful
    doWork(arg)
  }
}

class ChildFunction extends ParentFunction {
  override def doWork(arg: String): String = "Did something special"
}

Alternately, make the useful bit a different abstraction:

object UsefulTool {
  def withNotification(f: => String) {
    useful
    f
  }
  def useful = ???
}

Then you can wrap any work:

UsefulTool.withNotification {
  "Did something special"
}

And of course, pass in methods for ease of testing:

def doSpecial: String = "Did something special"

val result = UsefulTool.withNotification doSpecial _

Upvotes: 1

Kigyo
Kigyo

Reputation: 5768

I hope i understood your problem correctly. You could define that in the apply of ParentFunction and just let the children pass a Function[String, String].

class ParentFunction(func: String => String) extends Function[String, String] {
  def useful: Any = println("useful")

  def apply(s: String) = {
    useful
    func(s)
  }
}

object ChildFunction extends ParentFunction(
  s => "Did something special, and something generally useful! " + s
)

println(ChildFunction("child"))

which prints:

useful
Did something special, and something generally useful! child

Upvotes: 1

Related Questions