【问题标题】:is there any way to use import someValue._ to implement overriding methods in scala?有什么方法可以使用 import someValue._ 在 scala 中实现覆盖方法?
【发布时间】:2013-09-26 08:22:29
【问题描述】:

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

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> 

...以某种方式导致子类通过导入覆盖父方法?基本上,我认为能够在没有所有打字的情况下使用组合会很有趣。只是好奇这样的事情是否可能。

【问题讨论】:

  • 是的,我意识到这一点,只是想知道是否有任何方法可以使这样的事情发挥作用。它可以使具有大量抽象方法的特征的组合变得容易。
  • 因为我想要从现有实例中实现...而实际上该特征可能有 20 多种方法。由于大多数特征的大小,Scala 中的组合通常需要大量输入。我的手累了。
  • 您可能想查看 AutoProxy 编译器插件。这个问题有一些信息:Proxies / delegates in Scala
  • @DaoWen 这个问题已经很老了,但我只是添加了一个反映最近发展的答案。如果这方面还有其他工作,我会鼓励其他人也这样做。
  • @Brian import 只是将符号带入您的词法命名空间,这是正确的(想象一下由于粗心的通配符导入而意外为您实现方法的混乱)。代表似乎是一个更有希望的解决方案。但是,与此同时,您应该考虑“Scala 中的组合......需要大量输入”,或者您的用例是否需要不同的 type 组合(请参阅@Shadowlands 答案) .

标签: scala inheritance overriding


【解决方案1】:

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

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

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

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

【讨论】:

  • 这正是我一直在寻找的东西。由于它仍然只是一个概念验证,我将无法在任何生产代码中使用它,但我喜欢它的存在,我可能会尝试使用它。谢谢!
【解决方案2】:

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

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

【讨论】:

  • 这样的事情可能会有所帮助,但我不能说“with someAlreadyInstantiatedInstance”......我希望重新使用指定参数中存在的实现。
猜你喜欢
  • 1970-01-01
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-02
  • 1970-01-01
  • 1970-01-01
  • 2018-08-22
相关资源
最近更新 更多