Return multiple values from a function in Kotlin
This article covers different ways to return multiple values from a function in Kotlin.
1. Using Data class
The idiomatic way of returning multiple values from a function is to define your data class and return its instance from the function. Then you can unpack values using destructuring declaration inside the caller function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
data class Person(var name: String, var age: Int, var gender: Char) fun fetchPersonDetails(): Person { val name = "Riya" val age = 18 val gender = 'M' return Person(name, age, gender) } fun main() { val (name, age, gender) = fetchPersonDetails() // destructuring declaration println("($name, $age, $gender)") // (Riya, 18, M) } |
2. Using Pair/Triple class
Kotlin has generic Pair and Triple types that can return two or three values from the function. Note that it’s preferred to have your data named properly, and we should use a data class to return more values.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun fetchPersonDetails(): Triple<String, Int, Char> { val name = "Riya" val age = 18 val gender = 'M' return Triple(name, age, gender) } fun main() { val (name, age, gender) = fetchPersonDetails() println("($name, $age, $gender)") // (Riya, 18, M) } |
3. Returning an array
Another approach is to accumulate your values inside an array and return it from the function. Note that this doesn’t offer type safety for an object array or pass field information to the caller.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun fetchPersonDetails(): Array<Any> { val name = "Riya" val age = 18 val gender = 'M' return arrayOf(name, age, gender) } fun main() { val (name, age, gender) = fetchPersonDetails() println("($name, $age, $gender)") // (Riya, 18, M) } |
That’s all about returning multiple values from a function in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)