Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

kotlin

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?

In swift we do it like following,

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

can we achieve this in Kotlin?

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.

like image 457
AwaisMajeed Avatar asked Nov 15 '17 12:11

AwaisMajeed


People also ask

How can I return multiple values from a function in Swift?

Tuples can be used to return multiple values from Swift functions. A tuple allows you to group together multiple values of different types which can then be returned from a function as a single entity.

How do I return a triple in Kotlin?

If there is a need to return more than one value of a different data types, then we can create a class and declare all the variables that we want to return from the function and after that create an object of the class and easily collect all the returned values in a list.

How does a function return a value in Kotlin?

To return values, we use the return keyword. In the example, we have two square functions. When a funcion has a body enclosed by curly brackets, it returns a value using the return keyword. The return keyword is not used for functions with expression bodies.


1 Answers

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() 
like image 92
zsmb13 Avatar answered Sep 18 '22 00:09

zsmb13