混合特征示例

时间:2015-07-22 02:38:56

标签: scala traits

鉴于以下一般服务:

scala> trait Service[A, B] { def login: Either[A, B] }
defined trait Service

虽然未显示,但有两项服务使用Service#login

scala> trait CreateService extends Service[String, Int] {
     |   def create = ???
     | }
defined trait CreateService

scala> trait DeleteService extends Service[Boolean, Int] {
     |   def delete = ???
     | }
defined trait DeleteService

然后,在我们的MainApp中,例如在Web服务中定义路由,我们需要这两种服务:

scala> object MainApp extends CreateService with DeleteService {}
<console>:13: error: illegal inheritance;
 object MainApp inherits different type instances of trait Service:
Service[Boolean,Int] and Service[String,Int]
       object MainApp extends CreateService with DeleteService {}
              ^

但是,发生上述编译时错误。

CreateServiceDeleteServiceMainApp的功能混合在一起的正确方法是什么?

0 个答案:

没有答案