Returning multiple data
Although Kotlin doesn't provide a multiple return feature, thanks to data classes and destructuring declarations, it is quite convenient to write functions that return a number of values of different types. In this recipe, we are going to implement a function returning the result of dividing two numbers. The result is going to contain the quotient and remainder values.
How to do it...
- Let's start with declaring a data class for the return type:
data class DivisionResult(val quotient: Int, val remainder: Int)
- Let's implement the
divide()function:
fun divide(dividend: Int, divisor: Int): DivisionResult {
val quotient = dividend.div(divisor)
val remainder = dividend.rem(divisor)
return DivisionResult(quotient, remainder)
}How it works...
We can see the divide() function in action:
val dividend = 10
val divisor = 3
val (quotient, remainder) = divide(dividend, divisor)
print("$dividend / $divisor = $quotient r $remainder")The preceding code is going to print the following output...