问题很简单,我有一个对象用两个参数进行二元运算。我只想添加具有相同类型的燃料,如下所示:
object Fuels {
case class Fuel[F <: FuelType](amount: Double, fuelType: F = Petrol) {
def +(that : Fuel[F]) = {
copy(amount = this.amount + that.amount)
}
}
def add[F <: FuelType](x: Fuel[F], y: Fuel[F]): Fuel[F] = x + y
sealed trait FuelType {
val name : String
}
case object Petrol extends FuelType{
override val name = "Petrol"
}
case object Diesel extends FuelType{
override val name = "Diesel"
}
case object Hydrogen extends FuelType{
override val name = "Hydrogen"
}
implicit def fuelMonoid[F <:FuelType](implicit fuelType: F) = new Monoid[Fuel]{
override def zero: Fuel[F] = Fuel(0, fuelType)
override def append(m1: Fuel[F], m2: Fuel[F]) : Fuel[F] = m1 + m2
}
}
用它:
> Fuel(10, Petrol) + Fuel(20, Petrol)
> add(Fuel(10, Petrol), Fuel(10, Petrol))
编译错误:
Expression of Type Fuels.Fuel[Nothing] does not conform to Fuels.Fuel[F]
主要问题是 add 和fuelMonoid 都无法识别我们正在处理相同类型的项目。编译器无法解析类型约束,并推断 Nothing。
为了完成,这里是 Monoid,没什么特别的:
trait Monoid[A] {
def zero: A
def append(a1: A, a2: A): A
}