Search code examples
kotlinrx-kotlin

Kotlin lambda syntax confusion


I'm confused by Kotlin lambda syntax.

At first, I have

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

which works fine.

Then I moved the onNext to another class called GroupRecyclerViewAdapter which implements Action1<ArrayList<Group>>.

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

However, I got the error:

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

I can fix the error by changing to:

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

Is there a way to write the lambda without specifying a type? (Action1<kotlin.Throwable>, Action0)

Note: subscribe is RxJava method

Edit 1

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

Solution

  • view.adapter as GroupRecyclerViewAdapter part should be lambda func, not Action, since onError and onComplete also lambdas

    so, to fix this try:

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

    with your names (replace Unit with your type)

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

    with lambdas

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

    with actions

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

    pick one