Issue
I have a SwitchPreferenceCompat
with the key legacy_storage
. I want to run some code when this preference is disabled or enabled in the SettingsFragment
, but the code to run depends on the new state of the preference. I've tried using
class="lang-kotlin prettyprint-override">findPreference<SwitchPreferenceCompat>("legacy_storage")?.setOnPreferenceChangeListener { preference, newValue ->
if (newValue) { // if enabled
// do some stuff...
} else { // if disabled
// do other stuff...
but it says Type mismatch: inferred type is Unit but Boolean was expected
. I can't change the lambda definition to specify Boolean, because it says Type mismatch: inferred type is (Preference!, java.lang.Boolean) -> kotlin.Boolean but ((Preference!, Any!) -> kotlin.Boolean)! was expected
.
I've also tried .to(Boolean)
, but it says Type mismatch: inferred type is Pair<Boolean, ???> but Boolean was expected
.
Solution
The listener lambda must return a Boolean that indicates whether it handled the change. Typically you just want to return true unless you're doing something complicated with multiple listeners on the same preference. To return something from a lambda, put it on the last line of the lambda. This is why your error message was talking about Unit--your if/else expression was evaluating to a Unit and was the last expression of the lambda.
And newValue
is an Any
that you have to cast to Boolean
or alternatively test equality against true
. This is because the OnPreferenceChangeListener interface does not use generics.
findPreference<SwitchPreferenceCompat>("legacy_storage")?.setOnPreferenceChangeListener { preference, newValue ->
if (newValue == true) {
} else {
}
true
}
Answered By - Tenfour04
Answer Checked By - Marilyn (JavaFixing Volunteer)