【问题标题】:Scala trait composition issueScala trait 组合问题
【发布时间】:2012-08-14 22:29:23
【问题描述】:

我有一个无法修改源的类:

class Foo {

  def bar() = println("bar")

}

还有一个我想在运行时混入其中的特征

trait Zee { this: Foo =>

  abstract override def bar() = {
    println("before bar")
    super.bar()
  }
}

这是在扔bar is not a member of Object with ScalaObject

我做错了什么?是否可以在不修改Foo源的情况下实现这一点?

最终的客户端代码需要如下所示:

val foo = new Foo with Zee
foo.bar() // should print 'before bar' and then 'bar'

【问题讨论】:

    标签: scala traits


    【解决方案1】:

    你的 Zee trait 没有 super trait(除了从 ScalaObject 的隐式继承),因此 super 不包含 bar 的定义,并且没有什么可以覆盖或调用 (super.bar)。

    你为什么不写这个没有自我参考?

    class Foo {
    
      def bar() = println("bar")
    
    }
    
    
    trait Zee extends Foo {
    
      abstract override def bar() = {
        println("before bar")
        super.bar()
      }
    }
    

    【讨论】:

      【解决方案2】:

      你可以在你的 trait 中扩展类 Foo:

      trait Zee extends Foo
      

      您的代码将起作用。

      【讨论】:

        【解决方案3】:

        你的特质需要extend foo

        trait Zee extends Foo {
          abstract override def bar() = {
            println("before bar")
            super.bar()
          }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-18
          • 1970-01-01
          • 2013-11-26
          相关资源
          最近更新 更多