Home > Mobile >  How to pass a parameterized function from a object to a lambda function of other class in Kotlin
How to pass a parameterized function from a object to a lambda function of other class in Kotlin

Time:12-30

I have a function fun submitFormWithData(abc: String) in my ViewModel class, the viewModel object is used in other class from where I just want to pass the function submitFormWithData, not the viewModel object, I'm able to pass a parameterized function to the other function if the function in the same class however if the function is accessed from a object it become difficult.

Below is an example:

class ViewModel {

  fun submitForm() {
     // do some thing
     }

  fun submitFormWithData(abc: String) {
    // do some thing
    }
}  


class Screen(viewModel: MyViewModel) {

      fun main() {
          BuildHeader(viewModel.submitForm)
          BuildFooter(viewModel.submitFormWithData)
        }

      @Composable
      fun BuildHeader(submitForm:()->Unit){
          // some code
          btn.click -> {
               submitForm.invoke()
                     }
       }

      @Composable
      fun BuildFooter(submitFormWithData:(String)->Unit){
      // some code
      btn.click(data: String) -> {
         submitFormWithData.invoke(data)
            }
     }

     fun dataInSameClass(data: String) {

       }

}

In the above example class Screen has a lambda function BuildFooter which accept a parameterized function, if I want to pass a function from same class fun dataInSameClass I can simply use :: operator or encapsulate the function with curly brace for no parameter {dataInSameClass} eg.

// for parameterized function insame calss BuildFooter(::dataInSameClass) // for no parameter function insame calss BuildFooter({dataInSameClass()})

However if I want to pass a function from the object viewModel I'm not able to do it, I'm able to pass function which has no parameter, eg.

For no parameter, which works fine: BuildFooter({viewMode.submitForm()})

For parameterized function, dosn't works: BuildFooter(::viewMode.submitFormWithData)

If I try {viewMode.submitFormWithData()} it ask me to pass parameter, Here I don't want to pass the parameter since the data will be passed where the actual call happen, same as when I do ::dataInSameClass, I don't want to pass the complete viewModel object I just want to pass the function with parameter.

CodePudding user response:

You should write it as

fun main() {
    BuildHeader(viewModel::submitForm)
    BuildFooter(viewModel::submitFormWithData)
}
  • Related