I'm trying to add an onPreferenceClickListener within my SettingsFragment and if I do it like this:
signOutPref.setOnPreferenceClickListener(object: Preference.OnPreferenceClickListener {
override fun onPreferenceClick(preference: Preference?): Boolean {
val signOutIntent = Intent(activity, SignInActivity::class.java)
startActivity(signOutIntent)
return true
}
})
It works perfectly while giving a warning:
Use property access syntax
While if I write it like this:
signOutPref.setOnPreferenceClickListener {
val signOutIntent = Intent(activity, SignInActivity::class.java)
startActivity(signOutIntent)
return true
}
which should be the exactly the same thing and it's the best way to do it, I get a:
The Boolean literal does not conform to the expected type Unit
on the return true statement.
What am I missing? Is the second way to do it different than the first? How do I get rid of this error?
In a lambda, the last statement automatically becomes the returned value unless it's return type is inferred as Unit. So simply remove return.
signOutPref.setOnPreferenceClickListener {
val signOutIntent = Intent(activity, SignInActivity::class.java)
startActivity(signOutIntent)
true
}
The documentation says:
A lambda expression is always surrounded by curly braces, parameter declarations in the full syntactic form go inside curly braces and have optional type annotations, the body goes after an -> sign. If the inferred return type of the lambda is not
Unit, the last (or possibly single) expression inside the lambda body is treated as the return value.
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