我们如何像在swift中那样从Kotlin中的函数返回多个值?

Awa*_*eed 39 android kotlin

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

我试图返回一天中的时间,我需要将小时,分钟和秒作为单独的整数返回,但是所有这一切都来自同一个函数,这可能吗?

在快速我们这样做,如下,

func getTime() -> (Int, Int, Int) {
    ...
    return ( hour, minute, second)
}
Run Code Online (Sandbox Code Playgroud)

我们可以在Kotlin实现这一目标吗?

PS:我知道我可以使用Array或Hashmap,但我想知道kotlin中是否存在类似于swift的东西.

zsm*_*b13 74

您不能在Kotlin中创建任意元组,而是可以使用数据类.一种选择是使用内置的PairTriple通用的类,并且可以分别保存两个或三个值.您可以将这些结合使用这样的解构声明:

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

val (num, str) = getPair()
Run Code Online (Sandbox Code Playgroud)

您还可以构造一个ListArray多个前五个元素:

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

val (a, b, c, d, e) = getList()
Run Code Online (Sandbox Code Playgroud)

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

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()
Run Code Online (Sandbox Code Playgroud)


Mah*_*rim 13

虽然通常一个函数只能返回一个值,但在 Kotlin 中,通过利用 Pair 类型和解构声明的优点,我们可以从一个函数返回两个变量。考虑以下示例:

fun getUser():Pair<Int,String> {//(1) 
  return Pair(1,"Mahabub") 
} 

fun main(args: Array<String>) { 
  val (userID,userName) = getUser()//(2) 
  println("User ID: $userID t User Name: $userName") 
} 
Run Code Online (Sandbox Code Playgroud)

来自:功能性 Kotlin 书


Mar*_*uin 6

根据 Kotlin 文档(https://kotlinlang.org/docs/reference/multi-declarations.html#example-returning-two-values-from-a-function),你可以这样实现:

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

fun getTime(): TimeData {
    // do your calculations

    return TimeData(hour, minute, second)
}

// Get the time.
val (hour, minute, second) = getTime()
Run Code Online (Sandbox Code Playgroud)


Eke*_*eko 6

看来您已经知道创建特定的类来处理时间的明显答案。因此,我想您正在尝试避免创建类或访问数组的每个元素等麻烦,而是在寻找额外代码方面最短的解决方案。我会建议:

fun getTime(): Triple<Int, Int, Int> {
    ...
    return Triple( hour, minute, second)
}
Run Code Online (Sandbox Code Playgroud)

并在解构中使用它:

var (a, b, c) = getTime()
Run Code Online (Sandbox Code Playgroud)

如果需要4或5个返回值(不能解构超过5个),请使用Array

fun getTime(): Array<Int> {
    ...
    return arrayOf( hour, minute, second, milisec)
}
Run Code Online (Sandbox Code Playgroud)

var (a, b, c, d) = getTime()
Run Code Online (Sandbox Code Playgroud)

PS:解构时使用的变量要少于值的数量,例如,var (a, b) = getTime()但不能使用更多的变量,否则会得到ArrayIndexOutOfBoundsException


Jib*_*bin 5

使用 Triple 返回 3 个值,使用 Pair 返回 2 个值

class Book(val title: String, val author: String, val year: Int) {


fun getTitleAuthor(): Pair<String, String> {
    return (title to author)
}

fun getTitleAuthorYear(): Triple<String, String, Int> {
    return Triple(title, author, year)
}}
Run Code Online (Sandbox Code Playgroud)