Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Preference.setOnPreferenceClickListener

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?

like image 389
Daniele Avatar asked Oct 22 '25 12:10

Daniele


1 Answers

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.

like image 117
s1m0nw1 Avatar answered Oct 25 '25 01:10

s1m0nw1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!