You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin的Pair对象中比较元素并返回值更小的对象

解决方法

你遇到的问题核心是直接比较price返回的是数值类型,而非对象本身。下面提供几种实用方案,直接返回属性值更小的对象:

方案1:使用带比较器的minOf重载

Kotlin的minOf有支持自定义比较逻辑的重载版本,直接传入两个对象,并指定以price为比较依据,返回的就是目标对象:

// 假设你的对象结构类似这样
data class Store(val storeName: String, val price: Double)

fun getCheaperStore(pair: Pair<Store, Store>): Store {
    return minOf(pair.first, pair.second) { a, b ->
        a.price.compareTo(b.price)
    }
}

// 调用示例
val pair = Pair(Store("A店", 15.9), Store("B店", 12.5))
val cheaper = getCheaperStore(pair)
println(cheaper.storeName) // 输出 B店

这个重载的函数签名是fun <T> minOf(a: T, b: T, comparator: Comparator<in T>): T,lambda里的逻辑就是告诉函数:用两个对象的price来比较大小。

方案2:让对象实现Comparable接口

如果你的两个对象类型一致(或者可以通过接口统一),可以让它们实现Comparable接口,这样就能直接用原生的minOf函数:

// 定义统一接口并实现Comparable
interface PricedStore : Comparable<PricedStore> {
    val storeName: String
    val price: Double

    override fun compareTo(other: PricedStore): Int {
        return price.compareTo(other.price)
    }
}

// 你的两个对象实现该接口
data class Object1(override val storeName: String, override val price: Double) : PricedStore
data class Object2(override val storeName: String, override val price: Double) : PricedStore

// 直接调用minOf
fun getCheaperStore(pair: Pair<PricedStore, PricedStore>): PricedStore {
    return minOf(pair.first, pair.second)
}

这样只要对象属于PricedStore类型,minOf就会自动用你定义的price比较逻辑返回更小的对象。

方案3:直接用if判断(简单场景首选)

如果逻辑很简单,没必要用函数重载或接口,直接通过if-else判断更直观:

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

这种写法代码量最少,适合不需要复用比较逻辑的场景。

内容的提问来源于stack exchange,提问作者SNM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 07:40:44