具有多态类型的有限状态机?

A Finite State Machine with Polymorphic Types?

我想创建一个有限状态机,其中...

类型 A 的事物可以转换为 B、C 或 D,而类型 B、C 或 D 的事物只能转换回 A。它们可以转换为任何其他状态,但只能通过 A。

我希望 Scala 编译器帮助我,并通过 Ops 为我提供一些糖分 class,但我遇到了一个可爱、有用的 "not available" 错误。

Whosebug 有什么建议吗?

// let's start with some coproducts
sealed trait Color
trait Red extends Color
trait Blue extends Color

// define a car whose behavior should, for this
// example, be a function of the color of the car
final case class Car[A](make: String, model: String)

trait Paintshop[C[_], From, To] {
  def paint(car: C[From]): C[To]
}

object Paintshop {
  implicit val redCarsCanBePaintedBlue = new Paintshop[Car, Red, Blue] {
    override def paint(car: Car[Red]): Car[Blue] = Car[Blue](car.make, car.model)
  }
}

object CarOps {
  implicit class CarOps(car: Car[Red]) {
    def paint(implicit P: Paintshop[Car, Red, Blue]): Car[Blue] = P.paint(car)
  }
}

// now to make the magic happen
// let's paint a Red Car Blue
import CarOps._
val car = Car[Red]("Honda", "Civic").paint[Blue]

唉; .paint 不适用于 Car[Red]! pourquoi?

objectimplicit class 不能同名。

重命名implicit class CarOpsimplicit class CarOpsX即可编译成功