问题
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