How to find min/max of class properties and return its object?

Viewed 502

I have some class objects

class City (val name: String) {
    var degrees: Int = 0
}
val city1 = City("city1")
city1.degrees = 10
val city2 = City("city2")
city2.degrees = 20
val city3 = City("city3")
city3.degrees = 30

How to find min/max of degrees of 3 cities and return it's object?

1 Answers

You can put them in a list (or other iterable) and then use minByOrNull or maxByOrNull:

val cityWithMaxDegrees = listOf(city1, city2, city3).maxByOrNull { it.degrees }

Note that if the list is empty, maxByOrNull will return null, so you would have to handle it. This is also the case for the deprecated maxBy/minBy, which is the reason why they have been deprecated. In the future, maxBy/minBy can be reintroduced with non-null return types and throwing exceptions in case of empty list.

Related