Home > Software design >  How to compare two objects in a Pair and return the max one
How to compare two objects in a Pair and return the max one

Time:02-02

I have an object of type Pair<Object1, Object2>, now I'm trying to return the object in which the comparison of its values is lower.

I see in kotlin that we have the followin function

/**
 * Returns the smaller of two values.
 * 
 * If values are equal, returns the first one.
 */
@SinceKotlin("1.1")
public actual fun <T : Comparable<T>> minOf(a: T, b: T): T {
    return if (a <= b) a else b
}

This one should work for me, since I need to see which of the two objects has its minimum value and return that object

so I'm expecting to return the object as

minOf(pair.first.price, pair.second.price).storeName

But this one yields into the Double comparator

How can I add the comparator for these two objects and return the object that has the min value ?

CodePudding user response:

if (pair.first.price <= pair.second.price) pair.first else pair.second

CodePudding user response:

Your question lacks some details about your data structure and what does it mean the object is lower. However, if I understand your example correctly, this is how you can do this:

minOf(pair.first, pair.second, compareBy { it.price }).storeName

Alternatively, we can do it more concisely by converting to a list, although I think this could be misleading and it is not worth the performance hit:

pair.toList().minBy { it.price }.storeName
  • Related