Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 函数继承-在子.apply()上的超类中调用方法_Scala - Fatal编程技术网

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

Scala 函数继承-在子.apply()上的超类中调用方法,scala,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 somet

假设我有以下几点:

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的任何其他后代?

我希望我正确理解了您的问题。您可以在应用
ParentFunction
中定义它,然后让孩子们传递一个
函数[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

最简单的方法就是不要让孩子们提供
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 _

我不认为这是op想要的:“除了显式调用‘有用’之外,不确定他是不是也在apply方法中。子类现在不必处理
有用的
。我猜这就是他的意图。