在 scala 中使用具有函数的 mixin 组合

Using mixin composition with functions in scala

我正在尝试使用函数使用 mixin 组合,但我在 obj 对象的 apply 方法中遇到错误:

覆盖方法适用于 (s: String)String 类型的 trait t;方法 apply 需要 abstract override 修饰符。

如何解决这个错误,哪个是正确的实施方式?

trait t extends Function1[String,String] {
  abstract override def apply(s: String): String = {
    super.apply(s)
    println("Advice" + s)
    s
  }
}

object MixinComp {
  def main(args: Array[String]) {
    val obj = new Function1[String, String] with t {
      override def apply(s: String) = s
    }
    println(obj.apply("Hi"))
  }
}

如果不调用 super.apply,则无需在 t 特征定义中使用 abstract 修饰符。在这种特殊情况下,我认为没有必要调用 super.apply,因为 Function1 的应用是抽象的。您可能需要自定义应用实现。以下代码应该可以工作。

trait t extends Function1[String, String] {
  override def apply(s: String): String = {
    // super.apply(s)
    println("Advice" + s)
    s
  }
}

案例 1:在 t 特征中使用覆盖的 apply 方法:

val obj = new Function1[String, String] with t {} 
obj.apply("hello") // prints: Advicehello

案例 2:在匿名 class:

中覆盖 t trait 中的 apply 方法
val obj = new Function1[String, String] with t {
  override def apply(s: String): String = s
}

obj.apply("hello") // prints hello

您的直接问题(它抱怨错误的原因)是您不能在线性化流程中进行抽象调用(您的 t.apply 调用 super.apply,这是抽象的)。

另外,你在顶层匿名class中定义的apply方法覆盖了一切,并没有调用super,使得t完全混入无关紧要。

这样的事情可以解决这两个问题:

trait t extends Function1[String,String] {
  abstract override def apply(s: String): String = {
    println("Advice" + s)
    super.apply(s) // I rearranged this a little, because it kinda makes more sense this wat
  }
}

 // Note, this extends `Function1`, not `t`, it, just a "vanilla" Function1
class foo extends Function1[String, String] {
   def apply(s: String): String = s
}


// Now I am mixing in the t. Note, that the apply definition 
// from foo is now at the bottom of the hierarchy, so that 
// t.apply overrides it and calls it with super 
val obj = new foo with t
obj("foo")