代码之家  ›  专栏  ›  技术社区  ›  skjagini

Scala如何允许使用类型参数而不是类型类重写

  •  0
  • skjagini  · 技术社区  · 7 年前

    有没有想过为什么不支持方法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 回复  |  直到 7 年前
        1
  •  3
  •   Gonzalo Guglielmo    7 年前

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

    所以你要做的是:

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