在编程中,函数通常只能返回一个值。但通过使用对象封装、Pair、Triple、数组、列表或 Bundle 方式,可以轻松地返回多个值。
1、对象封装方式
- 创建数据类来封装需要返回的多个值。
data class Result(val code: Int, val message: String)fun getMultiValues(): Result {return Result(1, "success")}// 调用方式val result = MultiReturnUtils.getMultiValues()
2、Pair 或 Triple 方式(kotlin)
- Kotlin 提供了 Pair 和 Triple 类,可以用来返回两个或三个值。
fun getMultiValuesByPair(): Pair<Int, String> {return Pair(1, "success")}// 调用方式val (code, message) = MultiReturnUtils.getMultiValuesByPair()
fun getMultiValuesByTriple(): Triple<Int, String, Boolean> {return Triple(1, "success", true)}// 调用方式val (code, message, flag) = MultiReturnUtils.getMultiValuesByTriple()
3、数组或列表方式
- 如果需要返回多个相同类型的值,可以使用数组或列表。
fun getMultiValuesByList(): List<Int> {return listOf(1, 2, 3)}// 调用方式val list = MultiReturnUtils.getMultiValuesByList()
4、Bundle 方式(Android 特有)
- 在 Android 开发中,Bundle 是一个常用的数据容器,可以用来传递多个值。
fun getMultiValuesByBundle(): Bundle {val bundle = Bundle()bundle.putInt("code", 1)bundle.putString("message", "success")return bundle}// 调用方式val bundle = MultiReturnUtils.getMultiValuesByBundle()val code = bundle.getInt("code")val message = bundle.getString("message")