Lambda参数应移出括号 [英] Lambda argument should be moved out of parentheses

查看:88
本文介绍了Lambda参数应移出括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IntelliJ提出以下投诉:

IntelliJ gives the following complaint:

Lambda参数应移出括号

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?

推荐答案

sortedWith():返回根据元素排序的所有元素的列表指定的[比较器]

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

因此,要对 profile 列表进行排序,您必须将 sortedWith()返回的列表分配给 profile (还要将其声明从 val var )

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) }

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
})

警告:按Alt + Enter并让InteliJ进行更改.

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

这篇关于Lambda参数应移出括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆