Kotlin三元组(Triple)
外观
Kotlin三元组(Triple)[编辑 | 编辑源代码]
Kotlin三元组(Triple)是标准库提供的用于存储三个任意类型值的通用数据类,属于Kotlin的元组(Tuple)概念实现之一。它允许将三个独立的值作为单一逻辑单元传递,常用于需要临时组合数据的场景。
基本特性[编辑 | 编辑源代码]
- 不可变性:一旦创建,三个元素的值不可修改(类似于`val`声明)
- 类型安全:支持泛型,三个元素可以是不同类型
- 解构声明:支持直接将元素解构到独立变量
- 实现原理:通过`data class`实现,自动生成`equals()`、`hashCode()`和`toString()`
数学表示:
创建与访问[编辑 | 编辑源代码]
基础用法[编辑 | 编辑源代码]
// 创建三元组
val userData = Triple("Alice", 28, false)
// 访问元素(三种方式)
println(userData.first) // 输出: Alice
println(userData.second) // 输出: 28
println(userData.third) // 输出: false
// 类型推断示例
val coordinates = Triple(12.5, 4.8, -3.2) // Triple<Double, Double, Double>
解构声明[编辑 | 编辑源代码]
val (name, age, isPremium) = userData
println("$name (${age}岁) ${if(isPremium) "VIP" else "普通用户"}")
// 输出: Alice (28岁) 普通用户
类型参数[编辑 | 编辑源代码]
三元组支持完整的泛型参数:
fun <A, B, C> createTriple(a: A, b: B, c: C): Triple<A, B, C> = Triple(a, b, c)
val mixedTriple = createTriple("Text", 42, listOf(1, 2, 3))
// 类型为 Triple<String, Int, List<Int>>
实际应用案例[编辑 | 编辑源代码]
案例1:函数多返回值[编辑 | 编辑源代码]
fun parseDate(input: String): Triple<Int, Int, Int> {
val parts = input.split("-")
return Triple(parts[0].toInt(), parts[1].toInt(), parts[2].toInt())
}
val (year, month, day) = parseDate("2023-11-15")
案例2:图形坐标处理[编辑 | 编辑源代码]
fun translatePoint(
point: Triple<Double, Double, Double>,
dx: Double, dy: Double, dz: Double
): Triple<Double, Double, Double> {
return Triple(point.first + dx, point.second + dy, point.third + dz)
}
案例3:数据库查询结果[编辑 | 编辑源代码]
// 模拟数据库行记录
fun getUserRow(id: Int): Triple<String, String, Int> {
// 实际中可能来自数据库查询
return when(id) {
1 -> Triple("user1", "user1@example.com", 150)
2 -> Triple("user2", "user2@example.com", 210)
else -> Triple("guest", "no-email", 0)
}
}
与Pair的比较[编辑 | 编辑源代码]
特性 | Triple | Pair |
---|---|---|
元素数量 | 3 | 2 |
适用场景 | 需要三个关联值 | 需要两个关联值 |
解构变量 | `(first, second, third)` | `(first, second)` |
替代方案 | 数据类 | 数据类/Map.Entry |
高级用法[编辑 | 编辑源代码]
集合操作[编辑 | 编辑源代码]
val points = listOf(
Triple(1, 2, 3),
Triple(4, 5, 6),
Triple(7, 8, 9)
)
// 计算所有点的z坐标和
val sumZ = points.sumOf { it.third } // 输出: 18
作为Map的键[编辑 | 编辑源代码]
需确保所有组件类型实现了`hashCode()`:
val cache = mutableMapOf<Triple<String, Int, String>, BigDecimal>()
cache[Triple("USD", 30, "buy")] = BigDecimal("123.45")
限制与替代方案[编辑 | 编辑源代码]
当需要更多元素或更复杂结构时,建议使用数据类:
// 替代Triple的推荐方式
data class UserProfile(
val name: String,
val age: Int,
val isVerified: Boolean
)
选择依据:
- 需要语义化字段名时
- 元素数量超过3个时
- 需要添加自定义方法时
最佳实践[编辑 | 编辑源代码]
1. 优先为业务逻辑创建明确的数据类 2. 临时性数据组合可使用Triple 3. 避免深度嵌套(如`Triple<Triple<...>, ...>`) 4. 公共API考虑使用命名参数增强可读性
页面模块:Message box/ambox.css没有内容。
在Android开发中,Parcelable数据不建议使用Triple,应实现明确的数据类。 |