我尝试概括一种方法来提供类型安全的 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
}
关于scala - Scala 中的方法泛化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44945189/