Kotlin 通配符方法

Kotlin wildcard method

我在 RxJava 中使用 retryWhen 函数时遇到一些问题。

当我在 Observable 中创建要传递给 retryWhen 的函数时,我无法调用 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)报错:

Type mismatch: Expecting out Throwable, found in 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和return的期望值?

找到解决方案:

it.cast(Throwable::class.java).zipWith

或者这个:

(observable as Observable<Throwable>).zipWith

Throwable转换解决,希望Kotlin有别的方法(不依赖Observable.cast方法)。