4

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?

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
Daniele
  • 4,163
  • 7
  • 44
  • 95

2 Answers2

8

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.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
1

You have to use return@setOnPreferenceClickListener true.

Explanation

Quoting from this anser:

In Kotlin, the return@label syntax is used for specifying which function among several nested ones this statement returns from.

user2340612
  • 10,053
  • 4
  • 41
  • 66
karandeep singh
  • 2,294
  • 1
  • 15
  • 22