How to return multiple values from a function in Kotlin like we do in Swift?

It seems that you are aware of the obvious answer of creating a specific class to handle time. So I guess you are trying to avoid the small hassle of creating a class, or accessing each element of an array, etc. and are looking for the shortest solution in terms of extra code. I would suggest:

fun getTime(): Triple<Int, Int, Int> {
    ...
    return Triple( hour, minute, second)
}

and use it with deconstruction:

var (a, b, c) = getTime()

If you need 4 or 5 return values (you cannot deconstruct more than 5), go with Array:

fun getTime(): Array<Int> {
    ...
    return arrayOf( hour, minute, second, milisec)
}

and

var (a, b, c, d) = getTime()

P.S.: you can use less variables than there are values when deconstructing, like var (a, b) = getTime() but you cannot use more or you'll get an ArrayIndexOutOfBoundsException


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()

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()

While, generally, a function can return only a single value, in Kotlin, by leveraging the benefits of the Pair type and destructuring declarations, we can return two variables from a function. Consider the following example:

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") 
} 

From: Functional Kotlin book

Tags:

Android

Kotlin