首页 > 解决方案 > 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
}

标签: scalagenerics

解决方案


在 FooImpl2 的实现中,您将 BarImpl 作为 FooImpl2 的新类型参数传递,而不是将其传递给 Foo2(即需要类型参数的参数)。

所以你要做的是:

class FooImpl2 extends Foo2[BarImpl] {
    override def bar1(f: BarImpl): Boolean = true
}

推荐阅读