【问题标题】:Type inference failed Kotlin rxjava map use类型推断失败 Kotlin rxjava 地图使用
【发布时间】:2018-11-15 12:26:49
【问题描述】:

试图添加一个compositeDisposable。使用下面的代码:

 compositeDisposable.add(
        animalsObservable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .filter { s -> s.toLowerCase().startsWith("c") }
            .map(object : Function<String, String>()
            {
                @Throws(Exception::class)
                fun apply(s: String): String
                {
                    return s.toUpperCase()
                }
            })
            .subscribeWith(animalsObserverAllCaps)
    )
    }

但是,我收到以下错误:

类型推断失败:fun map(p0: Function!): Observable! 不能应用于 ()
类型不匹配:推断类型是但函数!预料之中
接口函数需要一种类型参数

【问题讨论】:

    标签: android kotlin rx-java rx-android


    【解决方案1】:

    我希望它像这样简单:

    .map { it.toUpperCase() }
    

    代替

    .map(object : Function<String, String>()
    {
        @Throws(Exception::class)
        fun apply(s: String): String
        {
            return s.toUpperCase()
        }
    })
    

    但无论如何,您可能没有使用io.reactivex.functions.Function,因此会出现错误。如果你真的不想使用 lambda,那么:

    .map(object : io.reactivex.functions.Function<String, String> {
        override fun apply(t: String): String {
            return t.toUpperCase()
        }
    })
    

    或者直接导入io.reactivex.functions.Function,然后使用Function

    【讨论】:

    • 不幸的是,不是。它最终会出现 s 的错误,因为未解决。
    • 是的,我的错,参数的默认名称是it。我更新了答案。
    猜你喜欢
    • 2018-05-03
    • 1970-01-01
    • 2018-08-21
    • 2020-12-30
    • 2018-05-15
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多