且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Scala中将方法参数限制为子类类型

更新时间:2023-11-01 19:43:46

  1. 您可能希望使用<:(子类型)而不是:(

  1. You probably want <: (subtype) instead of : (context bound).

this.type 并不代表您的意思(它是

this.type doesn't mean what you think it means (it is the type which only has this (and null) as value, not "the current type").

如果您解决了这些问题,则投射

If you fixed those problems, the cast in

override def add[G <: SimpleGameStatistics](s: G): G =
  SimpleGameStatistics((equity * nrGames + s.equity * s.nrGames) / (nrGames + s.nrGames), nrGames + s.nrGames).asInstanceOf[G]

没有道理;您刚刚创建了 SimpleGameStatistics 的实例,将其强制转换为子类将引发异常.

wouldn't make sense; you just created an instance of SimpleGameStatistics, casting it to a subclass would throw an exception.

但是您似乎想要 F界多态性:>

But it looks like you want F-bounded polymorphism:

trait GameStatistics[G <: GameStatistics[G]] { this: G =>
  def equity: Double

  def add(s: G): G

  def multiply(x: Double): G
}

object GameStatistics {
  def aggregate[G <: GameStatistics[G]](stats: Seq[G]): G = stats.reduce( _ add _ )
}

case class SimpleGameStatistics(equity: Double, nrGames: Int) extends GameStatistics[SimpleGameStatistics] {

  override def add(s: SimpleGameStatistics): SimpleGameStatistics =
    SimpleGameStatistics((equity * nrGames + s.equity * s.nrGames) / (nrGames + s.nrGames), nrGames + s.nrGames)

  override def multiply(x: Double): SimpleGameStatistics = SimpleGameStatistics(equity * x, nrGames)
}