Reputation: 538
Here is my code which is not working:
val people = listOf(Person("Tarun", 28), Person("Shyam", 25), Person("Pushpraj", 27))
people.maxBy { Person::age }
Error which am getting for above code:
Type parameter bound for R in inline fun <T, R : Comparable<R>> Iterable<T>.maxBy(selector: (T) -> R): T?
is not satisfied: inferred type KProperty1<Person, Int> is not a subtype of Comparable<KProperty1<Person, Int>>
Working code:
val people = listOf(Person("Tarun", 28), Person("Shyam", 25), Person("Pushpraj", 27))
people.maxBy { it.age }
Not able to understand the issue here.
Upvotes: 1
Views: 502
Reputation: 2039
people.maxBy(Person::age)
would work (watch the brackets)
The maxBy function has following signature:
public inline fun <T, R : Comparable<R>> Iterable<T>.maxBy(selector: (T) -> R): T? {
If you write people.maxBy { Person::age }
, it could be written as people.maxBy( { Person::age } )
which means you pass a lambda which returns another lambda (Supplier) which returns the INT age.
In other words: you pass (java Supplier) lambda inside other lambda instead of the actual (java Supplier) lambda. It looks confusing because you can remove normal brackets in Kotlin if the last argument in the method is a lambda.
Upvotes: 3