【问题标题】:Using mixin composition with functions in scala在scala中使用带有函数的mixin组合
【发布时间】:2016-10-04 02:01:06
【问题描述】:

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

覆盖方法适用于trait t 类型的(s: String)String;方法 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"))
  }
}

【问题讨论】:

    标签: scala function mixins


    【解决方案1】:

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

    此外,您在顶级匿名类中定义的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")
    

    【讨论】:

      【解决方案2】:

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

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

      案例1:使用t trait 中覆盖的apply 方法:

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

      案例 2:在匿名类中覆盖 t trait 中的 apply 方法:

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

      【讨论】:

      • 这没有回答问题
      猜你喜欢
      • 2015-03-19
      • 2017-02-16
      • 2014-03-28
      • 2021-04-09
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多