I want to use a lambda rather than an anonymous class for OnCheckedChangeListener.
The original code for setting the listener works fine and reads:
mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
mCrime.setSolved(isChecked);
}
});
I tried changing it to a lambda by doing:
mCheckBox.setOnCheckedChangeListener(l -> mCrime.setSolved(isChecked));
but I receive an error from Android Studio saying: cannot resolve symbol is checked.
I had thought a lambda would resolve isChecked implicitly even though the onCheckChanged takes two arguments. What is wrong with my understanding?
If you want to replace all the lambda expression from the project you can try Ctrl + Shift+ Alt + I on inspection search tab, search anonymous type can be replaced with lambda. It will replace all the anonymous type to lambda. With Studio 3.5.
Generally speaking, lambdas and streams provide a more concise and (once everyone is up to speed) more readable way of expressing this kind of algorithm.
It helps to iterate, filter and extract data from collection. The Lambda expression is used to provide the implementation of an interface which has functional interface. It saves a lot of code. In case of lambda expression, we don't need to define the method again for providing the implementation.
Your syntax is wrong. What you have shouldn't even compile. Use this:
mCheckBox.setOnCheckedChangeListener((view, isChecked) -> mCrime.setSolved(isChecked));
The stuff before the ->
doesn't represent the listener, but rather the arguments that are passed in that listener, in this case a View and a boolean.
isChecked is just a parameter name it is not there when you are using lambdas how ever here is the correct lambda with the parameter names for your onCheckChangeListener
mCheckBox.setOnCheckedChangeListener((CompoundButton.OnCheckedChangeListener) (buttonView, isChecked) -> mCrime.setSolved(isChecked));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With