组成子类以实现类型限制

时间:2017-01-17 11:04:06

标签: scala subclass type-resolution

我是Scala的新手并且正在学习编写个人项目。

我有这个问题,环顾四周并没有多大帮助。所以这是 -

abstract class Service{
 def containsFeatures(x: Feature*) = ??? 
 } 

object Service1 extends Service{..
 def containsFeature(x: Feature*)
 }

object Service2 extends Service{..
 def containsFeature(x: Feature*)
 }

Trait Feature

case object A extends Feature
case object B extends Feature
case object C extends Feature
case object D extends Feature
case object E extends Feature
case object F extends Feature
case object G extends Feature

我想以这样的方式限制我的代码,即Service1定义哪些功能可能而哪些功能是错误的。 例如:     Service1允许组合对象A,C,E,G,并在提供其他功能时显示错误。

这是否可以通过我们的Service1定义以编程方式限制它而不修改其他类?

我希望我的问题足够明确。

感谢您的任何建议。

1 个答案:

答案 0 :(得分:0)

如果您希望scalac在编译时在提供错误的Feature时显示错误,并且您不能更改Service1以外的任何内容,那么就不可能。编译器根据其接口接受或拒绝对Service1.containsFeature的调用,但其接口已在Service中定义,表示它将接受任何 Feature

如果您可以更改其他代码的内容,有一些方法可以执行此操作。例如,如果你可以改变一切:

scala> :paste
// Entering paste mode (ctrl-D to finish)

abstract class Service[Allowed <: Feature] {
  def containsFeatures(x: Allowed*): Unit
} 

object Service1 extends Service[S1Feature] {
  def containsFeatures(x: S1Feature*): Unit = println("ok")
}

object Service2 extends Service[S2Feature] {
  def containsFeatures(x: S2Feature*): Unit = println("ok")
}

sealed trait Feature
sealed trait S1Feature extends Feature
sealed trait S2Feature extends Feature

case object A extends S1Feature
case object B extends S2Feature
case object C extends S1Feature
case object D extends S2Feature
case object E extends S1Feature
case object F extends S2Feature
case object G extends S1Feature

// Exiting paste mode, now interpreting.

scala> Service1.containsFeatures(A,B,C)
<console>:16: error: type mismatch;
 found   : B.type
 required: S1Feature
       Service1.containsFeatures(A,B,C)
                                   ^

scala> Service1.containsFeatures(A,C,G)
ok