Lambda expression not used

When using Android Switch I attached setOnCheckedChangeListener to it and received this warning

Lambda expression is not used. If you mean a block, you can use "run {...}"

Here is the code snippet:

 switchAction.setOnCheckedChangeListener({ _, isChecked -> { preferences.userStatus = isChecked switchToggleVisibility(isChecked) if (isChecked) { fetchStats() getOrders() } else { releaseOrder() } } }) 

Using run resolves this warning, but does anyone know the reason for this? How is a lambda expression not used?

+5
source share
2 answers

You mix the designation of the Java lambda with the Kotlin musical notation, creating a lambda that returns in this case another nested lambda. The correct and idiomatic syntax would look like this:

 switchAction.setOnCheckedChangeListener { _, isChecked -> preferences.userStatus = isChecked switchToggleVisibility(isChecked) if (isChecked) { fetchStats() getOrders() } else { releaseOrder() } } 

Taking in all the noise, a normal lambda looks like this:

 { arg1, arg2 -> returnValue } 

You did it:

 { arg1, arg2 -> { returnValue } } 

What can also be written like this:

 { arg1, arg2 -> { -> returnValue } } 

This notation makes it a little clearer that a lambda does not return a return value, but returns another lambda without parameters returning a return value.

Usually this will depend on the compiler as the wrong return type, but in your case, the return value of the lambda is not used. So, you just create an inner lambda without returning or starting it, so you get a warning.

+11
source

Yes,

 _, isChecked -> { ... } 

Need to change to

 _, isChecked -> preferences.userStatus = isChecked switchToggleVisibility(isChecked) if (isChecked) { fetchStats() getOrders() } else { releaseOrder() } 

So, just remove the curly braces, because otherwise you just create a block that doesn't execute at all. Alternatively you can also do

 _, isChecked -> run { preferences.userStatus = isChecked switchToggleVisibility(isChecked) if (isChecked) { fetchStats() getOrders() } else { releaseOrder() } } 
+2
source

Source: https://habr.com/ru/post/1270049/


All Articles