zm chen
zm chen

Reputation: 3

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

Upvotes: 0

Views: 47

Answers (1)

Amin
Amin

Reputation: 241

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

Upvotes: 1

Related Questions