Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda argument should be moved out of parentheses

Tags:

kotlin

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?

like image 226
Johann Avatar asked Nov 19 '18 13:11

Johann


1 Answers

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.

like image 163
Cililing Avatar answered Sep 20 '22 14:09

Cililing