Kotlin通配符方法
我在使用retryWhen
中的retryWhen
函数时遇到了一些问题。
当我创建一个函数传递给retryWhen
在一个Observable
,我不能调用zipWith
函数。 看来Kotlin正在等待一些不能在这里施展的东西。
在这个例子中, it.zipWith
不起作用(一些其他方法可用,但不是这个):
val retryFunc = Func1<Observable<out Throwable>, Observable<Any>> { // zipWith is not possible to call it.zipWith<Int, Any>(Observable.range(1, 3), Func2<Throwable, Int, Any> { throwable, integer -> if (integer > 2) { return@Func2 Observable.error<Any>(Exception()) } Observable.timer(1, TimeUnit.SECONDS) }) } Observable.just("1", "2", "3").retryWhen(retryFunc)
如果我将传入的参数更改为Func1<Observable<in Throwable> ...
,则in
关键字可以使用zipWith
函数。 但是,我改变后,调用retryWhen(retryFunc)
显示一个错误:
类型不匹配:期望Throwable Throwable,在Throwable中找到
val retryFunc = Func1<Observable<in Throwable>, Observable<Any>> { it.zipWith<Int, Any>(Observable.range(1, 3), Func2<Throwable, Int, Any> { throwable, integer -> if (integer > 2) { return@Func2 Observable.error<Any>(Exception()) } Observable.timer(1, TimeUnit.SECONDS) }) } Observable.just("1", "2", "3").retryWhen(retryFunc) // type mismatch here, expected out, found in
有谁知道我怎样才能收到和生产相同类型的Kotlin?
能够创建zipWith
并返回期望值?
找到了解决办法:
it.cast(Throwable::class.java).zipWith
或者这个:
(observable as Observable<Throwable>).zipWith
用Throwable
解决方案投射,我希望Kotlin有另一种方法(不依赖于Observable.cast
方法)。