scala中的协变类型参数需要在java接口中保持不变
我有一个看起来像这样的特征(一些进一步的信息可以在 这个相关问题中找到我自己虽然我不认为,但这个问题需要它)
trait Extractor[-A,+B] {
def extract(d:A):B
//lots of other things
}
要在现有的java框架中使用它,我希望这个Extractor
有一个返回Comparator的函数[B]
(是 java.util .Comparator)或者更好地扩展Comparator[A]
。现在这就带来了一个问题,因为 Comparator 的类型参数应该是不变的,而 A 是逆变的,B 是协变的。
所以我收到这样的错误:
scala> import java.util.Comparator
import java.util.Comparator
scala> trait Extractor[-A,+B] extends Comparator[A]
<console>:6: error: contravariant type A occurs in invariant position in type [-A,+B]java.lang.Object with java.util.Comparator[A] of trait Extractor
trait Extractor[-A,+B] extends Comparator[A]
^
scala> trait Extractor[-A, +B] {
| def comp:Comparator[B]
| }
<console>:7: error: covariant type B occurs in invariant position in type => java.util.Comparator[B] of method comp
def comp:Comparator[B]
^
您是否看到了解决此问题的方法,或者这只是“在 scala 中使用 java 泛型会造成伤害”的情况之一?
I've got a trait that looks like this (some further information can be found at this related question by myself although I don't think, it's needed for this question)
trait Extractor[-A,+B] {
def extract(d:A):B
//lots of other things
}
To use this in an existing java framework I would like this Extractor
to either have a function that returns a Comparator[B]
(being java.util.Comparator) or even better extend Comparator[A]
. Now that poses a problem because Comparator
s type parameter is ought to be invariant, while A
is contravariant and B
is covariant.
So I get errors like this:
scala> import java.util.Comparator
import java.util.Comparator
scala> trait Extractor[-A,+B] extends Comparator[A]
<console>:6: error: contravariant type A occurs in invariant position in type [-A,+B]java.lang.Object with java.util.Comparator[A] of trait Extractor
trait Extractor[-A,+B] extends Comparator[A]
^
scala> trait Extractor[-A, +B] {
| def comp:Comparator[B]
| }
<console>:7: error: covariant type B occurs in invariant position in type => java.util.Comparator[B] of method comp
def comp:Comparator[B]
^
Do you see any way out of this or is this just one of those cases where "using java generics in scala hurts"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
@uncheckedVariance
注解使Extractor[A,B]
扩展Comparator[A]
。@uncheckedVariance
在这里是安全的,因为Comparator
可以定义为Comparator[-T]
。有一个关于为 Scala 2.8 制作Ordering
协变的讨论使用这个注释。编辑请参阅此问题了解有关
@uncheckedVariance
的更多信息。You can make
Extractor[A,B]
extendComparator[A]
by using the@uncheckedVariance
annotation.@uncheckedVariance
is safe here becauseComparator
could have been defined asComparator[-T]
. There was a discussion around makingOrdering
covariant for Scala 2.8 using this annotation.Edit See this question for more about
@uncheckedVariance
.在类型限制的帮助下,可以执行以下操作:
With help of type-bounds it's possible to do the following: