When “sharing” generics across traits, contravariant error for parameters of that type

淺唱寂寞╮ 提交于 2019-12-25 06:35:02

问题


I want to share the type defined in class Base with class SometimesUsedWithBase

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
}

This solution worked fine until I added the parameter to someFunction of type BaseType. (so if you remove the parameter, the code works fine). Now I get this error:

Error:(7, 21) covariant type _$1 occurs in contravariant position in type SometimesUsedWithBase.this.BaseType of value in def someFunction(in: BaseType): BaseType ^

Any ideas how I can accomplish what i'm looking to do?


回答1:


Here is working code:

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
}

I don't think you should use both generic type parameter and assign it to a type, you have same information twice.

To use generics you need to pase the type around which is what you don't want, but it compiles as well

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
}


来源:https://stackoverflow.com/questions/37056136/when-sharing-generics-across-traits-contravariant-error-for-parameters-of-tha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!