我正在查看 scala types of types self types annotation
它表示 new Service
无法实例化,因为 self type
的使用有利于 extends
。但是我也用 extends
尝试了这个例子,但它仍然没有编译。
class TryMe {
class ServiceInModule {
def doTheThings() = "dfdf"
}
trait Module {
lazy val serviceInModule = new ServiceInModule
}
trait Service extends Module {
def doTheThings() = serviceInModule.doTheThings()
}
trait TestingModule extends Module {
}
new Service
}
Error:(22, 3) trait Service is abstract; cannot be instantiated new Service ^
我错过了什么吗?为什么它声称使用 extends 它应该编译?它不编译...
最佳答案
trait就像java中的增强接口(interface),不能直接创建。您需要对其进行子类化,这就是您通过添加 {} 所做的。
所以你需要做
new Service {}
并且您创建的不是服务实例,而是扩展服务特征的“匿名类”
关于scala self type 在使用 `extends` 时真的可以编译吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27551969/