如何使用带构造函数的抽象类扩展Scala中的对象?

Poo*_*oya 2 scala

如何使用具有构造函数的抽象类扩展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
   }
}
Run Code Online (Sandbox Code Playgroud)

我认为一个很好的解决方案是:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我的问题是我无法编辑AbstractResource

sen*_*nia 5

我不知道为什么要Wood扩展AbstractResource,但这有效:

class AbstractResource(val amount:Int) {
  def getAmount = amount
}

case object Wood extends AbstractResource(0) {
  def apply(amount: Int) = {
    new AbstractResource(amount)
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @Pooya什么是中间抽象类? (3认同)