嗯,你正在踩踏Scala中使用的Java泛型的方差问题.我们一步一步走吧.
我们来看看你的实现:
// does not compile (with your original error)
def timeout[U >: T](timeout: Duration,otherJava))
}
要理解为什么这不起作用,让我们在thisJava的声明中调用A未命名的类型(A
// still does not compile,sadly
def timeout[U >: T](timeout: Duration,other: Observable[U]): Observable[U] = {
val otherJava: rx.Observable[_ <: u other.asjavaobservable>
val thisJava: rx.Observable[U] = this.asJavaObservable // variance error
toScalaObservable[U](thisJava.timeout(timeout.length,otherJava))
}
在一个完美的世界中,上述方法将起作用.但是,java rx.Observable未定义为协变,因为java中没有定义 – 站点方差注释.所以Scala认为它是不变的.
因此就Scala而言,rx.Observable [_应该是协变的,所以我们可以盲目抛弃:
// this compiles and *should* work
def timeout[U >: T](timeout: Duration,other: Observable[U]): Observable[U] = {
val otherJava: rx.Observable[_ <: u other.asjavaobservable>
val thisJava = this.asJavaObservable.asInstanceOf[rx.Observable[U]]
toScalaObservable[U](thisJava.timeout(timeout.length,otherJava))
}
这个故事的寓意是,混合Scala的方差和Java的方差总是会让你在这里和那里花费一些时间,必须仔细考虑.
另外,使asJavaObservable返回一个rx.Observable [T]而不是_