Kotlin lambda 语法混淆

标签 kotlin rx-kotlin

我对 Kotlin lambda 语法感到困惑。

一开始我有

.subscribe(
          { println(it) }
          , { println(it.message) }
          , { println("completed") }
      )

效果很好

然后我将 onNext 移到另一个名为 GroupRecyclerViewAdapter 的类,它实现了 Action1<ArrayList<Group>> .

.subscribe(
          view.adapter as GroupRecyclerViewAdapter
          , { println(it.message) }
          , { println("completed") }
      )

但是,我得到了错误:

error

Error:(42, 17) Type mismatch: inferred type is () -> ??? but rx.functions.Action1<kotlin.Throwable!>! was expected
Error:(42, 27) Unresolved reference: it
Error:(43, 17) Type mismatch: inferred type is () -> kotlin.Unit but rx.functions.Action0! was expected

我可以通过更改为来修复错误:

.subscribe(
          view.adapter as GroupRecyclerViewAdapter
          , Action1<kotlin.Throwable> { println(it.message) }
          , Action0 { println("completed") }
      )

有没有办法在不指定类型的情况下编写 lambda?(Action1<kotlin.Throwable>Action0)

Note: subscribe is RxJava method

编辑 1

class GroupRecyclerViewAdapter(private val groups: MutableList<Group>,
                           private val listener: OnListFragmentInteractionListener?) :
RecyclerView.Adapter<GroupRecyclerViewAdapter.ViewHolder>(), Action1<ArrayList<Group>> {

最佳答案

view.adapter as GroupRecyclerViewAdapter 部分应该是 lambda func,而不是 Action,因为 onError 和 onComplete 也是 lambdas

所以,修复这个尝试:

.subscribe(
          { (view.adapter as GroupRecyclerViewAdapter).call(it) }
          , { println(it.message) }
          , { println("completed") }
      )

用你的名字(用你的类型替换 Unit)

class GroupRecyclerViewAdapter : Action1<Unit> {
    override fun call(t: Unit?) {
        print ("onNext")
    }
}

使用 lambdas

val ga = GroupRecyclerViewAdapter()
...subscribe(
    { result -> ga.call(result) },
    { error -> print ("error $error") },
    { print ("completed") })

有 Action

...subscribe(
    ga,
    Action1{ error -> print ("error $error") },
    Action0{ print ("completed") })

选择一个

关于Kotlin lambda 语法混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34966999/

相关文章:

java - Kotlin:如何从 Rxjava 一次输出 ArrayList

android-studio - Android Studio Kotlin Multiplatform 项目搞砸了自动完成

android - Jetpack Compose - 更改 viewModel 中的变量会导致 viewModel 状态发生更改吗?

android - 我对此Android Studio Kotlin程序有疑问:

intellij-idea - 如何在 IntelliJ 中的快速文档中包装文本?

kotlin - 打印 IntArray 内容的 Kotlin 方式是什么?

java - 使用 rx java 在非周期性间隔后发出事件

rx-java - RxJava 2 相当于 isUnsubscribed

lambda - RXKotlin Lambda 理解

android - 使用 collectInto 从 RxKotlin/RxJava 中的两个可观察源构建列表