3

我有这样的课:

abstract class CrudResource extends Controller {
  type ResourceIdType


  def getAction(id: ResourceIdType) = ...
  def deleteAction(id: ResourceIdType) = ...

  ...
}

打算像这样使用:

class Payees extends CrudResource {
  type ResourceIdType = Int

  ...
}

我想默认ResourceIdType为 Int,如下所示:

abstract class CrudResource extends Controller {
  type ResourceIdType = Int

  ...
}

这样 ID 类型将是Int除非子类像这样覆盖它:

override type ResourceId = String

但这无法编译:

error: overriding type ResourceIdType in class CrudResource, which equals Int;
 type ResourceIdType has incompatible type
       class Payees extends CrudResource { override type ResourceIdType = String }

有可能做我想做的事吗?我试过, in CrudResource, type ResourceIdType <: Any = Int,但这不是有效的语法。

4

4 回答 4

2

不确定您是否真的可以做到这一点,但泛型和继承可以很好地做到这一点:

abstract class CrudController [T] {

    def getAction( resource : T )
    def deleteAction( resource : T )
    def updateAction( resource : T )

}

abstract class IntCrudController extends CrudController [Int]

class PayeesController extends IntCrudController {

    override def getAction( resource : Int ) {}

    def deleteAction(resource: Int) {}

    def updateAction(resource: Int) {}
}
于 2012-06-20T01:43:23.853 回答
2

这将违反 liskov 替换原则。让我们假设你可以做到。

abstract class CrudResource extends Controller {
  type ResourceIdType = Int
  def resources: List[ResourceIdType] = ???
  def getAction(id: ResourceIdType) = ???
  def deleteAction(id: ResourceIdType) = ???
}

class Payees extends CrudResource {
  override type ResourceIdType = String
}

class Trouble {
  var resource: Controller.ResourceIdType
}
val trouble = new Trouble
val crudResource: CrudResource = new Payee
trouble.resource = crudResource.resources.head // assigning String to Int var!

但是,您已经完成了蛋糕模式的一半。如果将 ResourceId 定义为抽象嵌套类,则可以让子类根据Intor实现它们String,只要其 API 不公开特定类型即可。

于 2012-06-20T17:31:01.980 回答
1

Scala 的抽象类型在你定义之后就会被冻结。您不能在继承的类中用另一种类型覆盖一种类型

于 2012-06-20T13:14:57.353 回答
1

不,据我所知,这是不可能的。

于 2012-06-20T05:47:15.720 回答