Kotlin lambda syntax syntax

I am confused by the syntax of Kotlin's lambda.

I have first

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

which works great .

Then I moved 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 it to:

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

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

Note: Subscription is an RxJava Method

Change 1

 class GroupRecyclerViewAdapter(private val groups: MutableList<Group>, private val listener: OnListFragmentInteractionListener?) : RecyclerView.Adapter<GroupRecyclerViewAdapter.ViewHolder>(), Action1<ArrayList<Group>> { 
+7
kotlin rx-kotlin
source share
2 answers

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

therefore, to fix this attempt:

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

choose one

+7
source share

You have two versions of the subscribe method:

  • The first (real) has a signature subscribe(Action1<ArrayList<Group>>, Action1<Throwable>, Action0) .
  • The second version is generated by the Kotlin compiler and has a signature subscribe((ArrayList<Group>>) -> Unit, (Throwable) -> Unit, () -> Unit)

In your code, however, you pass the following types of parameters:

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

As you can see, these types of parameters do not satisfy any of the available signatures. Another answer gives you some solutions to your problem. In addition, you can make the GroupRecyclerViewAdapter implement the function type Function1<ArrayList<Group>, Unit> (these are also interfaces) instead of Action1<ArrayList<Group>> .

+2
source share

All Articles