Home > Net >  How to use Lambda function in Android
How to use Lambda function in Android

Time:06-27

In my application I have RecyclerView adapter and I want when click on Items, send some data to parent.
I want send model and string.
I write below codes, but after use show me error and I can't use this!

Lambda function in adapter :

    private var onItemClickListener: ((UserEntity) -> Unit)? = null
private var actionType: String? = null

fun setOnItemClickListener(listener: (UserEntity) -> Unit, type: String) {
    onItemClickListener = listener
    actionType = type
}

Use this function in Activity :

noteAdapter.setOnItemClickListener { listener: UserEntity, type: String ->
        }

Error message Image :
enter image description here

How can I fix it and use this function ?

CodePudding user response:

If you need access to both the objects i.e. NoteEntity & the String in the same listener, use like this :

private var onItemClickListener: ((UserEntity, String) -> Unit)? = null

fun setOnItemClickListener(listener: (UserEntity, String) -> Unit) {
    onItemClickListener = listener
}

After this, the lambda in the Activity should work fine.

noteAdapter.setOnItemClickListener { listener: UserEntity, type: String -> }
  • Related