有没有办法使用import someValue._来实现scala中的重写方法?

时间:2013-09-20 20:30:38

标签: scala inheritance override

有没有办法做这样的事情:

scala> trait Foo { def f:Int=0 }
defined trait Foo

scala> class FooImpl extends Foo { override val f = 1 }
defined class FooImpl

scala> class Bar(foo:Foo) extends Foo{ import foo._ }
defined class Bar

scala> (new Bar(new FooImpl)).f
res2: Int = 0

scala> trait Foo { def f:Int }
defined trait Foo

scala> class Bar(foo:Foo) extends Foo{ import foo._ }
<console>:8: error: class Bar needs to be abstract, since method f in trait Foo of type => Int is not defined
       class Bar(foo:Foo) extends Foo{ import foo._ }
             ^

scala> 

...以某种方式导致子类通过导入覆盖父方法?基本上我认为能够在没有所有打字的情况下使用构图会很有趣。如果有可能,这很奇怪。

2 个答案:

答案 0 :(得分:3)

您真正要求的是一种将方法实现委托给成员的方法。

此问题已在此处解决:Proxies / delegates in Scala

基本上,有一种方法可以使用宏来实现。可以在此处找到实施:https://github.com/adamw/scala-macro-aop

上面提供了一个@delegate宏注释,可以应用于数据成员,使编译器生成代码以将方法调用委托给该成员。请注意,宏注释是针对Scala 2.11计划的实验性功能,但您可以使用Macro Paradise编译器插件将它们与Scala 2.10一起使用。

答案 1 :(得分:1)

自我键入可以在这里提供帮助(具体取决于您将如何使用这些类 - 这不是实例的组合,更多类型的组合):

trait Foo { def f:Int }

trait FooImpl extends Foo { override val f = 1 } // Needs to be a trait to be mixed in.

class Bar {
  this: Foo =>  // This requires that any Bar instance must mix in a Foo (must 'be' a Foo)
}

然后,您可以实例化并使用类似于以下内容的Bar实例:

scala> (new Bar with FooImpl).f
res1: Int = 1