在編程中,函數通常只能返回一個值。但通過使用對象封裝、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")