IntelliJ gives the following complaint:
Lambda argument should be moved out of parentheses
val profile = loadProfiles()
profile.sortedWith(Comparator({ profile1, profile2 ->
if (profile1.age > profile2.age) return@Comparator 1
if (profile1.age < profile2.age) return@Comparator -1
return@Comparator 0
}))
data class Developer(var age: Int)
fun loadProfiles(): List<Developer> {
val listOfNumber = listOf<Developer>(Developer(2), Developer(5), Developer(3))
return listOfNumber
}
How should I format the above to get rid of the complaint? Also, the sorting code doesn't sort. What is causing the problem?
This warning is caused because in Kotlin lambda parameters can (and actually should be) outside parentheses.
See this:
fun onClick(action: () -> Unit) { ... }
When you use function like this you can use:
view.onClick({ toast(it.toString())} )
view.onClick() { toast(it.toString()) }
view.onClick { toast(it.toString()) }
All of those forms are correct (compiler will not fail), but in Kotlin Style Guide you'll find following statement:
If a call takes a single lambda, it should be passed outside of parentheses whenever possible.
@see https://kotlinlang.org/docs/reference/coding-conventions.html#lambda-formatting
That's why IntelliJ shows warning. You can press Alt+Enter and IntelliJ should show correct solution, or just move lambda out of parentheses. And if lambda is only argument remove parentheses also.
When lambda have to be in parentheses? Only when it is not last parameter in function.
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