如何使用具有构造函数的抽象类在 Scala 中扩展对象,并且对象的 apply 方法将对象作为抽象的子类型返回?
例如 :
abstract class AbstractResource(amount:Int) {
val amount:Int
def getAmount = amount
}
case object Wood extends AbstractResource{
def apply(amount: Int) = {
// something that returns the subtype
}
}
我认为一个好的解决方案是:
abstract class AbstractResource {
val amount: Int = 0
def getAmount = amount
}
case object Wood extends AbstractResource {
def apply(quantity: Int) = {
new AbstractResource {
override val amount = quantity
}
}
}
但我的问题是我无法编辑 AbstractResource