我试图概括一种提供类型安全API的方法,如下所示:

abstract class AbstractCommand {
  type T = this.type
  def shuffler(s: T => Seq[AbstractCommand])
}

class TestCommand extends AbstractCommand {
  override def shuffler(s: (TestCommand) => Seq[AbstractCommand]): Unit = ??? //error
}

我希望函数参数的预期类型在此层​​次结构中最具体。但这没有用。

有没有一种方法可以在Scala中执行类似的操作而无需引入一些辅助类型参数?

最佳答案

这看起来像是F-Bounded Polymorphism的完美用例:

abstract class AbstractCommand[T <: AbstractCommand[T]] {
  self: T =>
  def shuffler(s: T => Seq[AbstractCommand[T]])
}

class TestCommand extends AbstractCommand[TestCommand] {
  override def shuffler(s: (TestCommand) => Seq[AbstractCommand[TestCommand]]): Unit = ???
}

并且使用类型成员而不是类型参数(使用Attempting to model F-bounded polymorphism as a type member in Scala提供的示例):
abstract class AbstractCommand { self =>
  type T >: self.type <: AbstractCommand
}

class TestCommand extends AbstractCommand {
  type T = TestCommand
}

class OtherCommand extends AbstractCommand {
  type T = OtherCommand
}

07-26 06:02