【问题标题】:How Scala allows overriding with type parameters and not with type classScala 如何允许使用类型参数而不是类型类进行覆盖
【发布时间】:2019-04-24 02:36:19
【问题描述】:

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

【问题讨论】:

    标签: scala generics


    【解决方案1】:

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

    所以你要做的是:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 2015-02-18
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多