Kotlin lambda语法混淆

时间:2016-01-23 18:14:59

标签: 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>> {

2 个答案:

答案 0 :(得分:10)

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

带有动作

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

选择一个

答案 1 :(得分:2)

您有两种版本的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
)

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