函数继承 - 在child.apply()的超类中调用方法

时间:2014-08-23 17:10:15

标签: scala

假设我有以下内容:

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

除了显式调用'有用'之外,还有什么方法,我可以确保每当ChildFunction(或任何其他后代)调用'有用'是隐式 ParentFunction被调用?

2 个答案:

答案 0 :(得分:1)

我希望我能正确理解你的问题。您可以在申请ParentFunction时定义,然后让孩子通过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"))

打印:

useful
Did something special, and something generally useful! child

答案 1 :(得分:1)

最简单的方法是不让孩子提供apply,而是提供其他方法:

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

或者,将有用位设为不同的抽象:

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

然后你可以包装任何工作:

UsefulTool.withNotification {
  "Did something special"
}

当然,传递方法以便于测试:

def doSpecial: String = "Did something special"

val result = UsefulTool.withNotification doSpecial _