Scala复制方法返回不同的类型参数?

时间:2015-10-01 22:16:38

标签: scala

在以下示例中,如何在复制参数化类型时获取不同的类型参数:

sealed trait PreTax
sealed trait PostTax
case class Pay[State](s:String)
val pay = Pay[PreTax]("preTax")
val payPost:Pay[PostTax] = pay.copy(s="taxed")

1 个答案:

答案 0 :(得分:5)

你可以pay.copy[PostTax](s="taxed")

我认为有更好的方法可以对此进行建模。至少您应该将State类型参数限制为PreTaxPostTax

sealed trait Tax
sealed trait PreTax extends Tax
sealed trait PostTax extends Tax
case class Pay[State <: Tax](s:String)

这样您只能创建Pay[PreTax]Pay[PostTax]

更好的可能是:

sealed trait Pay { def s: String }
case class PayPreTax(s: String) extends Pay {
  def payTax(): PayPostTax = PayPostTax(this.s)
}
case class PayPostTax(s: String) extends Pay

object Pay {
  def apply(s: String): Pay = PayPreTax(s)
}

您可以将其用作:

scala> val pay = Pay("foobar")
pay: Pay = PayPreTax(foobar)

scala> pay match {
     |   case pre: PayPreTax => pre.payTax  // pay tax if not paid
     |   case post => post                  // tax is already paid
     | }
res8: Pay = PayPostTax(foobar)