是的,方法参数也可以是对类或接口的引用。并且方法参数也可以是对其他方法/函数/lambdas的引用。
如果您要处理难以概括的情况,请考虑使用某种控制反转(函数作为参数或 lambda)。
向 updateProperty 函数添加 lambda 参数
fun updateProperty(onUpdate: (viewBinding: YourViewBindingType, viewModel: YourViewModelType) -> Unit) {
//... other irrelevant code
// here you just call the lambda, with any parameters that might be useful 'on the other side'
onUpdate(viewBinding, viewModel)
//... other irrelevant code
}
代码中的其他地方 - 案例 1:
updateProperty() { viewBinding, viewModel ->
if (viewBinding.editText.text.toString() != "") {
viewModel.property.price = viewBinding.editText.text.toString().toDouble()
}
}
代码中的其他地方 - 案例 2:
updateProperty() { viewBinding, viewModel ->
if (viewBinding.secondEditText.text.toString() != "") {
viewModel.property.income = viewBinding.secondEditText.text.toString().toDouble()
}
}
代码中的其他地方 - 案例 3:
updateProperty() { viewBinding, viewModel ->
// I am a totally different case, because I have to update two properties at once!
viewModel.property.somethingElse1 = viewBinding.thirdEditText.text.toString().toBoolean()
viewModel.property.somethingElse2 = viewBinding.fourthEditText.text
.toString().replaceAll("[- ]*", "").toInt()
}
然后您可以更进一步,为前两种情况定义一个函数,因为这两种情况可以泛化,然后在 lambda 中调用它(甚至将其作为 lambda 传递),这将为您节省一些代码,如果您在代码中的许多地方调用updateProperty(),或者只是为它们中的每一个定义一个简单的函数,然后调用它,就像这样
fun updatePrice() = updateProperty() { viewBinding, viewModel ->
if (viewBinding.editText.text.toString() != "") {
viewModel.property.price = viewBinding.editText.text.toString().toDouble()
}
}
fun updateIncome() = updateProperty() { viewBinding, viewModel ->
if (viewBinding.secondEditText.text.toString() != "") {
viewModel.property.income = viewBinding.secondEditText.text.toString().toDouble()
}
}
然后在代码的其他地方你只需以非常简单的方式调用它
updatePrice()
updateIncome()