While using Android's Switch
, I was attaching a setOnCheckedChangeListener
to it and got this warning
The lambda expression is unused. If you mean a block, you can use 'run {...}'
Here' the code snippet:
switchAction.setOnCheckedChangeListener({
_, isChecked ->
{
preferences.userStatus = isChecked
switchToggleVisibility(isChecked)
if (isChecked) {
fetchStats()
getOrders()
} else {
releaseOrder()
}
}
})
Using run
does fix this warning, but does anyone know the cause behind this? How is the lambda expression unused?
You're mixing Java's lambda notation with Kotlin's lambda notation, creating a lambda that returns another nested lambda in this case. The correct and idiomatic syntax would look like this:
switchAction.setOnCheckedChangeListener { _, isChecked ->
preferences.userStatus = isChecked
switchToggleVisibility(isChecked)
if (isChecked) {
fetchStats()
getOrders()
} else {
releaseOrder()
}
}
Taking all the noise out, a normal lambda looks like this:
{ arg1, arg2 -> returnValue } // Type: (A, B) -> C
You did this:
{ arg1, arg2 -> { returnValue } } // Type: (A, B) -> (() -> C)
Which could also be written like this:
{ arg1, arg2 -> { -> returnValue } } // Type: (A, B) -> (() -> C)
This notation makes it a bit clearer that the lambda doesn't return the return value, but returns another lambda with no parameters that returns the return value.
Usually, this would get caught by the compiler as a wrong return type, but in your case, the return value of the lambda is not used. So, you're just creating the inner lambda without returning or running it, that's why you're getting a warning.
Yes, the
_, isChecked ->
{ ... }
Must be changed to
_, isChecked ->
preferences.userStatus = isChecked
switchToggleVisibility(isChecked)
if (isChecked) {
fetchStats()
getOrders()
} else {
releaseOrder()
}
So just remove the curly braces because else you just create a block which isn't executed at all. Alternatively you could also do
_, isChecked ->
run {
preferences.userStatus = isChecked
switchToggleVisibility(isChecked)
if (isChecked) {
fetchStats()
getOrders()
} else {
releaseOrder()
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.