scala中的Covariant类型参数需要在java接口中不变 [英] Covariant Typeparameter in scala needs to be invariant in java interface

查看:110
本文介绍了scala中的Covariant类型参数需要在java接口中不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的特质(一些进一步的信息可以在这个相关的问题,虽然我不认为,这是需要这个问题)

  trait提取器[-A ,+ B] {
def extract(d:A):B
//许多其他事物
}

要在现有的java框架中使用它,我希望这个 Extractor 有一个函数返回一个 Comparator [B] (正在 java.util.Comparator ),甚至可以更好地扩展 Comparator [A] 。现在,由于 Comparator 的类型参数应该是不变的,而 A 是逆变的,而<$ c

所以我得到这样的错误:

 阶> import java.util.Comparator 
import java.util.Comparator

scala> trait Extractor [-A,+ B]扩展Comparator [A]
< console>:6:error:逆变类型A出现在类型为[-A,+ B]的不变位置中,java中的java.lang.Object .util.Comparator [A]特征提取器
特征提取器[-A,+ B]扩展比较器[A]
^


scala>特质提取器[-A,+ B] {
| def comp:比较器[B]
| }
< console>:7:error:协变类型B出现在type =>中的不变位置上。方法comp
的java.util.Comparator [B] def comp:Comparator [B]
^

你是否看到过任何解决方法,或者这只是在scala中使用java泛型而痛苦的一种情况?

解决方案

  scala>在类型边界的帮助下,可以执行以下操作:

特质提取器[-A,+ B] {
| def comp:比较器[_<:B]
| }
定义特征提取器


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 Comparators 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"?

解决方案

With help of type-bounds it's possible to do the following:

scala> trait Extractor[-A, +B] {
     | def comp:Comparator[_ <: B]
     | }
defined trait Extractor

这篇关于scala中的Covariant类型参数需要在java接口中不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆