简体   繁体   English

定义其他特征的Scala特征

[英]Scala traits defining other traits

I ran into an interesting scenario in Scala. 我在Scala中遇到了一个有趣的场景。 It seems then I have a base trait that defines other traits, the implementation cannot find the base trait not matter what. 看来那么我有一个基础特征定义其他性状,实现无法找到基本特征没有关系的。

I created this base trait simple for convenience that I don't need to redefined these traits on every implementation. 为了方便起见,我创建了这个基本特征,我不需要在每个实现上都重新定义这些特征。 Do anyone know why this doesn't work? 有人知道为什么这行不通吗?

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. 
}

Update: 更新:
The question has been cleared up a bit so that its more precise. 这个问题已被清除,因此更加精确。 The solution as @BrianHsu pointed out is that trait cannot be inherited. @BrianHsu指出的解决方案是trait不能被继承。

This block of code is fine: 这段代码很好:

object Base {
  trait Event
  trait Command
}

The following block will run into to trouble: 以下块会遇到麻烦:

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

But Scala compiler says it very clearly. 但是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

Of course you cannot do this, just like you could not do the following in Java: 当然,您无法执行此操作,就像您无法在Java中执行以下操作一样:

class HelloWorld extends HelloWorld

You have to specify that what you extend is actually Base.Event / Base.Command, so it will only work if you write it as: 您必须指定扩展的内容实际上是Base.Event / Base.Command,因此只有将其编写为:

trait BaseTrait {
  trait Event extends Base.Event
  trait Command extends Base.Command
}

Another problem in your code it the last Something object, it does not make sense at all: 代码中的另一个问题是最后一个Something对象,这根本没有任何意义:

object Something {
  Implementation.Event
  Implementation.Commannd
}

So compiler give you a clear error message: 因此,编译器会为您提供明确的错误消息:

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

It's quite obvious, an trait in Scala is much like interface in Java, you should not use it as it is a field. 很明显,Scala中的一个特征与Java中的interface非常相似,您不应该使用它,因为它是一个字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM