Returning two values from a function

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,"Rivu") 
} 
fun main(args: Array<String>) { 
    val (userID,userName) = getUser()//(2) 
     println("User ID: $userID t User Name: $userName") 
} 

In the preceding program, on comment (1), we created a function that would return a Pair<Int,String> value.

On comment (2), we used that function in a way that seems like it returns two variables. Actually, destructuring declarations allows you to destructure a data class/Pair and get its underlying values in standalone variables. When this feature is used with functions, it seems like the function is returning multiple values, though it returns only one value that is a Pair value or another data class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.34.146