如何像在 Swift 中一样从 Kotlin 中的函数返回多个值? [英] How to return multiple values from a function in Kotlin like we do in Swift?

查看:19
本文介绍了如何像在 Swift 中一样从 Kotlin 中的函数返回多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 Kotlin 中的函数返回相同类型 (Int) 的 3 个单独数据值?

How to return 3 separate data values of the same type (Int) from a function in Kotlin?

我正在尝试返回一天中的时间,我需要将小时、分钟和秒作为单独的整数返回,但同时来自同一个函数,这可能吗?

I'm attempting to return the time of day, I need to return the Hour, Minute and Second as separate integers, but all in one go from the same function, is this possible?

在 swift 中,我们按照以下方式进行操作,

In swift we do it like following,

func getTime() -> (Int, Int, Int) {
    ...
    return ( hour, minute, second)
}

我们可以在 Kotlin 中实现这一点吗?

can we achieve this in Kotlin?

P.S:我知道我可以为此使用 Array 或 Hashmap,但我想知道 Kotlin 中是否存在类似 Swift 的东西.

P.S: I know I can use Array or Hashmap for this but I want to know if there exists something in Kotlin like it is in Swift.

推荐答案

你不能在 Kotlin 中创建任意的元组,你可以使用 数据类.一种选择是使用内置的 PairTriple 类是通用的,可以分别包含两个或三个值.您可以将这些与解构声明结合使用,如下所示:

You can't create arbitrary tuples in Kotlin, instead, you can use data classes. One option is using the built in Pair and Triple classes that are generic and can hold two or three values, respectively. You can use these combined with destructuring declarations like this:

fun getPair() = Pair(1, "foo")

val (num, str) = getPair()

您还可以解构 ListArray,直到第一个 5 个元素:

You can also destructure a List or Array, for up to the first 5 elements:

fun getList() = listOf(1, 2, 3, 4, 5)

val (a, b, c, d, e) = getList()

然而,最惯用的方法是定义您自己的数据类,它允许您从您的函数中返回一个有意义的类型:

The most idiomatic way however would be to define your own data class, which allows you to return a meaningful type from your function:

data class Time(val hour: Int, val minute: Int, val second: Int)

fun getTime(): Time {
    ...
    return Time(hour, minute, second)
}

val (hour, minute, second) = getTime()

这篇关于如何像在 Swift 中一样从 Kotlin 中的函数返回多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆