Search code examples
kotlinkotlin-extension

Member variables cannot be correctly converted to lambda expressions


As above

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

The above code is running correctly, when I convert to the following code, I can't get the correct result.

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

Solution

  • You should use it inside curly brackets and then access name and age. if you don't do that compiler accept your first argument( after this, other) that is name in this case as Person Object not String

    This code will work for you:

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