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

标签 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
   }
}

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

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

最佳答案

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

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

case object Wood extends AbstractResource(0) {
  def apply(amount: Int) = {
    new AbstractResource(amount)
  }
}

关于scala - 如何使用带构造函数的抽象类扩展 Scala 中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18097753/

相关文章:

scala - 在 Scala 3 中,如果泛型类型参数映射到依赖类型,那么协变和逆变修饰符是如何映射的?

java - 如何以全精度输出本地化的 Java 浮点值?

scala - java.lang.NoSuchMethodError : scala. Predef$.refArrayOps

scala - 分配帮助 : Union between sets

scala - 隐式使用结构类型

scala - 使 Scala 3 中的非详尽匹配编译失败

scala - Spark数据帧:How to add a index Column : Aka Distributed Data Index

Scala/Play http 身份验证问题 - 从请求中获取用户名和密码

scala - 匿名函数的参数类型必须是完全已知的。 (SLS 8.5)

scala - 将 (A => (M[B], M[C])) 转换为 (A => M[(B, C)])