定义其他特征的 Scala 特征

Scala traits defining other traits

我 运行 在 Scala 中遇到了一个有趣的场景。看来我有一个定义其他特征的 base trait,无论如何实现都找不到 base trait

为了方便,我创建了这个简单的基本特征,这样我就不需要在每个实现中都重新定义这些特征。有谁知道为什么这不起作用?

object Base {
   trait Create
   trait Delete
}

trait BaseTrait {
   trait Create extends Base.Create
   trait Delete extends Base.Delete
}

object Implementation extends BaseTrait 

object Something {
   class SomeClass extends Implementation.Create //The trait is not defined. 
}

更新:
这个问题已经被澄清了一点,这样它就更精确了。 @BrianHsu 指出的解决方案是无法继承 trait

这段代码没问题:

object Base {
  trait Event
  trait Command
}

以下块将 运行 引入麻烦:

trait BaseTrait {
  trait Event extends Event
  trait Command extends Command
}

但是Scala编译器说的很清楚。

test.scala:7: error: illegal cyclic reference involving trait Event
  trait Event extends Event
              ^
test.scala:8: error: illegal cyclic reference involving trait Command
  trait Command extends Command

当然你不能这样做,就像你不能在Java中那样做:

class HelloWorld extends HelloWorld

您必须指定您扩展的内容实际上是 Base.Event / Base.Command,因此只有您将其写为:

才有效
trait BaseTrait {
  trait Event extends Base.Event
  trait Command extends Base.Command
}

你代码中的另一个问题是最后一个 Something 对象,它根本没有意义:

object Something {
  Implementation.Event
  Implementation.Commannd
}

所以编译器给你一个明确的错误信息:

test.scala:14: error: value Event is not a member of object Implementation
  Implementation.Event
                 ^
test.scala:15: error: value Commannd is not a member of object Implementation
  Implementation.Commannd

很明显,Scala 中的 trait 很像 Java 中的 interface,你不应该使用它,因为它是一个字段。