Kotlin lambda 语法混乱

Kotlin lambda syntax confusion

我对 Kotlin lambda 语法感到困惑。

起初,我有

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

效果很好.

然后我将 onNext 移动到另一个 class 名为 GroupRecyclerViewAdapter 的实现 Action1<ArrayList<Group>>

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

但是,我得到了错误:

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")
    }
}

使用 lambda 表达式

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

有动作

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

选一个

您有两个版本的 subscribe 方法可供选择:

  • 第一个(真正的)有签名 subscribe(Action1<ArrayList<Group>>, Action1<Throwable>, Action0).
  • 第二个版本由 Kotlin 编译器生成,具有 签名 subscribe((ArrayList<Group>>) -> Unit, (Throwable) -> Unit, () -> Unit)

但是,在您的代码中,您传递了以下参数类型:

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

如您所见,这些参数类型满足 none 个可用签名。另一个答案为您提供了一些解决问题的方法。此外,您可以使 GroupRecyclerViewAdapter 实现功能类型 Function1<ArrayList<Group>, Unit>(它们也是接口)而不是 Action1<ArrayList<Group>>.