scala - Scala 如何允许使用类型参数而不是类型类进行覆盖
问题描述
有什么想法为什么不支持方法 2,还是我缺少任何语法?
trait Bar { }
class BarImpl extends Bar{ }
1 Scala 允许用泛型类型参数覆盖
abstract class Foo {
type T <: Bar
def bar1(f: T): Boolean
}
class FooImpl extends Foo {
type T = BarImpl
override def bar1(f: BarImpl): Boolean = true
}
2 虽然它不允许使用泛型类型类
abstract class Foo2[T <: Bar] {
def bar1(f: T): Boolean
}
class FooImpl2[BarImpl] extends Foo2 {
// Error: Method bar1 overrides nothing
override def bar1(f: BarImpl): Boolean = true
}
解决方案
在 FooImpl2 的实现中,您将 BarImpl 作为 FooImpl2 的新类型参数传递,而不是将其传递给 Foo2(即需要类型参数的参数)。
所以你要做的是:
class FooImpl2 extends Foo2[BarImpl] {
override def bar1(f: BarImpl): Boolean = true
}
推荐阅读
- function - 未来
' 不是类型 'Function? - amazon-web-services - 使用 aws lambda 时日志组不存在错误
- html - 使用 flex 右侧的徽标中心和菜单图标
- apache-kafka - 从特定时间戳开始流式传输 Kafka
- fluentlenium - Webdriver 实例在扩展 FluentTestNg 的测试类的测试方法后退出
- django - 通过从 Manager 中检查其中的字段值,将查询集中的模型值更改为 None
- python - 如何在子图中使用颜色图?
- android - Jetpack Compose 中的下拉按钮/滚轮选择器/微调器
- fortran - OpenMP 4.5/5.0 标准是否支持 GPU 上的 Fortran 自动数组?
- python - 如何在弹性搜索中索引文档?