问题描述
我想用class SometimesUsedWithBase来分享Base class中定义的类型
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $类型BaseType = A
}
trait SometimesUsedWithBase {
this:Base [_] =>
def someFunction(in:BaseType):BaseType
}
$ b $ class StringThing extends BaseUserWithBase {
def someFunction(in:String):String = + in
}
这个解决方案工作得很好,直到我将参数添加到someFunction键入BaseType。 (所以如果你删除参数,代码工作正常)。现在我得到这个错误:
$ b
任何想法
这里是工作代码:
trait Base {
type BaseType
}
trait SometimesUsedWithBase {this:Base =>
def someFunction(in:BaseType):BaseType
}
class StringThing extends Base With WithUseUsedWithBase {
type BaseType = String
def someFunction(in:String):String =+ in
}
t认为你应该使用泛型类型参数并将它分配给一个类型,你有两次相同的信息。
要使用泛型,你需要围绕这个类型你不想要,但它也可以编译
trait Base [A]
trait SometimesUsedWithBase [A] {this:Base [A] =>
def someFunction(in:A):A
}
class StringThing使用SometimesUsedWithBase [String] {
扩展Base [String] def someFunction(in:String) :String =+ in
}
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:
Any ideas how I can accomplish what i'm looking to do?
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
}
这篇关于当“共享”跨性状的泛型,该类型参数的逆变错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!