我试图概括一种提供类型安全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中做这样的事情,而不引入一些辅助类型参数?
答案 0 :(得分:4)
这看起来像是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
}
答案 1 :(得分:2)
您可以避免在抽象类中定义T:
abstract class AbstractCommand {
type T
def shuffler(s: T => Seq[AbstractCommand])
}
class TestCommand extends AbstractCommand {
type T = TestCommand
override def shuffler(s: (TestCommand) => Seq[AbstractCommand]): Unit = ??? //compiles !
}
在不利方面,它更加冗长,从好的方面来说,它更加通用!
答案 2 :(得分:2)
我并不完全确定它符合您的需求,但我已经能够编译并运行以下内容,请告诉我它是否有帮助:
import { MdChipsModule } from '@angular/material';
@NgModule({
...
imports: [MdChipsModule],
...
})
export class PizzaPartyAppModule { }