Scala如何允许使用类型参数而不是类型类进行覆盖

时间:2019-04-23 18:19:25

标签: scala generics

有什么想法为什么不支持方法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
}

1 个答案:

答案 0 :(得分:3)

在FooImpl2的实现中,您将BarImpl传递为FooImpl2的新Type参数,而不是将其传递给Foo2(这是需要type参数的那个)。

所以您要做的是:

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