【问题标题】:When "sharing" generics across traits, contravariant error for parameters of that type当跨特征“共享”泛型时,该类型参数的逆变错误
【发布时间】:2016-08-31 13:38:21
【问题描述】:

我想将类 Base 中定义的类型共享给类 AlsoUsedWithBase

trait Base[A] {
  type BaseType = A
}

trait SometimesUsedWithBase {
  this: Base[_] =>
  def someFunction(in: BaseType): BaseType
}

class StringThing extends Base[String] with SometimesUsedWithBase {
  def someFunction(in: String): String = "" + in
}

在我将参数添加到 BaseType 类型的 someFunction 之前,此解决方案运行良好。 (因此,如果您删除参数,则代码可以正常工作)。现在我得到这个错误:

错误:(7, 21) 协变类型 _$1 出现在逆变位置 在 def 中输入有时UsedWithBase.this.BaseType 的值 someFunction(in: BaseType): BaseType ^

有什么想法可以完成我想做的事情吗?

【问题讨论】:

  • 将类型参数添加到SometimesUsedWithBase[X]并在someFunction中使用
  • @rumoku 如果我这样做了,我将需要使用 StringThing 中的类型定义有时使用的WithBase,对吗?我希望避免这种情况,而是使用 Base 中定义的泛型

标签: scala generics types covariance


【解决方案1】:

这是工作代码:

trait Base {
  type BaseType
}

trait SometimesUsedWithBase { this: Base =>
  def someFunction(in: BaseType): BaseType
}

class StringThing extends Base with SometimesUsedWithBase {
  type BaseType = String

  def someFunction(in: String): String = "" + in
}

我认为你不应该同时使用泛型类型参数并将其分配给一个类型,你有两次相同的信息。

要使用泛型,您需要粘贴不需要的类型,但它也可以编译

trait Base[A]

trait SometimesUsedWithBase[A] { this: Base[A] =>
  def someFunction(in: A): A
}

class StringThing extends Base[String] with SometimesUsedWithBase[String] {
  def someFunction(in: String): String = "" + in
}

【讨论】:

    猜你喜欢
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多