Lambda argument should be moved out of parentheses

sortedWith(): Returns a list of all elements sorted according to the specified [comparator]

So to sort profile list you have to assign the list returned by sortedWith() to profile (also change its declaration from val to var)

var profile = loadProfiles()
profile = profile.sortedWith(Comparator { profile1, profile2 ->
    if (profile1.age > profile2.age) return@Comparator 1
    if (profile1.age < profile2.age) return@Comparator -1
    return@Comparator 0
})

profile.forEach { println(it.age) }

or

val profile = loadProfiles().sortedWith(Comparator { profile1, profile2 ->
    if (profile1.age > profile2.age) return@Comparator 1
    if (profile1.age < profile2.age) return@Comparator -1
    return@Comparator 0
})

For the warning: press Alt+Enter and let InteliJ make the change.


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.

Tags:

Kotlin