【问题标题】:Force trait to implement method强制特征实现方法
【发布时间】:2013-10-31 02:03:27
【问题描述】:

我有一个 trait I(中介)、一个类 M(混合器)和一个 trait S(特定)混合。

class M extends Something with S {
    def baz() = foo()
}

trait I {
    def foo(): { ...; bar(); ... }
    def bar()
}

trait S extends I {
    def bar() = 42
}

I 充当M 和S 之间的中间层,提供通用接口。

我在I 中有一个实现的方法foo,它调用了一个方法bar(未在I 中实现,但在那里定义)。我想要实现的是所有扩展I的特征必须实现bar,这样会抛出编译时错误,因为bar没有实现:

trait Z extends I

这在 Scala 中可行吗?

P.S.:我知道Force Scala trait to implement a certain method 的答案,但我不想要那种显式的耦合。

【问题讨论】:

  • 你不能强制 trait 实现类似的东西。
  • 我很好奇,你为什么需要那个?一旦您尝试对 I 进行具体实现(强制您提供 def 栏),您就会得到编译错误。但是一个特质本质上是抽象的……
  • 我需要它,因为特征和具体实现存在于单独的软件包中。这些特征在一个没有这些特征的具体用法的库中。我可以在我的测试套件中测试这些特征的正确实现。但是,如果错误已经在编译时弹出(例如在我的 IDE 中),我会更喜欢它。

标签: scala abstract traits concrete


【解决方案1】:

我不知道 Scala 中有什么方法可以强制一个特征对所有方法都有具体的实现。您可以编写一个宏来生成一个小的测试类,然后编译器将验证该测试类是具体的。编写一个接受此代码的宏应该不会太难:

@VerifyAllMethodsConcrete
trait Z extends I { ... }

并将其转换为以下代码:

trait Z extends I { ... }
class TestClassForVerifyingConcreteMethodsOfZ { }

现在,如果 trait Z 没有覆盖 bar(),将会有一个早期的错误提示 TestClassForVerifyingConcreteMethodsOfZ needs to be abstract。此错误消息并不完全清楚,但希望这可以在 Z 上进行您想要的早期验证。

【讨论】:

    【解决方案2】:

    这似乎是自我类型的一个用例:

    trait Z {
       self : I =>
    }
    

    编译器将检查层次结构中的任何类,包括Z 是或扩展I。

    【讨论】:

    • 你能添加一个例子吗?如果trait Z 没有定义bar(),我看不出我是如何得到编译时错误的。
    • 我认为使用 self 类型仍然无法强制 trait 实现某个方法。如果 class 使用 trait Z 并且 Z 没有提供实现,编译器将抛出错误。但正如我在previous comment 中所说,我想早点发现错误。
    【解决方案3】:

    我想到了结构子类型:

    trait I[T<: { def:foo:Unit}]
    

    ....

    这对你有用吗?

    【讨论】:

    • 这是您的想法吗? class M extends Object with S { def baz() = foo() } trait I[T &lt;: { def bar(): Unit }] { def foo() { bar() } def bar() } trait S extends I[S] { def bar() = 42 } 因为如果是这样,那么像 trait Q extends I[Q] { } 这样的东西仍然不会引发编译时错误。
    • 是的,我是这么想的。
    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多