我有一个这样的课程:
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 }
我可以做我想做的事吗?我尝试了CrudResource
,type ResourceIdType <: Any = Int
,但这不是有效的语法。
答案 0 :(得分: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) {}
}
答案 1 :(得分: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定义为抽象嵌套类,则可以使用Int
或String
实现它们的子类,只要其API不公开特定类型。
答案 2 :(得分:1)
不,据我所知,这是不可能的。
答案 3 :(得分:1)
Scala的抽象类型一旦定义就会冻结。您不能在继承的类
中覆盖另一种类型