成员变量无法正确转换为 lambda 表达式

Member variables cannot be correctly converted to lambda expressions

同上

data class Person(val name: String, val age: Int) : Comparable<Person> {
    override fun compareTo(other: Person): Int {
        return compareValuesBy(this, other, Person::name, Person::age)
    }
}

上面的代码是运行正确的,当我转换成下面的代码时,我无法得到正确的结果。

data class Person(val name: String, val age: Int) : Comparable<Person> {
    override fun compareTo(other: Person): Int {
        return compareValuesBy(this, other, { name }, { age })
    }
}

您应该在大括号内使用 it,然后访问姓名和年龄。如果你不这样做,编译器接受你的第一个参数(在 thisother 之后),即 name 在这种情况下是 Person Object 而不是 String

此代码适合您:

data class Person(val name: String, val age: Int) : Comparable<Person> {
  override fun compareTo(other: Person): Int {
    return compareValuesBy(this,other,{it.name},{it.age})
   }
}