Learning Kotlin – Part 7

In the last article we looked at functions in Kotlin.

But there is more to functions:

Multiple return values

All you Pythonistas already know the concept of multiple return values. Kotlin as a strongly typed language uses the Pair class to enable functions to return two values or Triple to return three.

fun nextTwo(num: Int) : Pair<Int, Int>{
    return Pair(num+1, num+2)
}
val(two, three) = nextTwo(1)
println("1 $two $three")

Variable argument list

 

fun getSum(vararg nums: Int) : Int{
    var sum = 0
    nums.forEach { n -> sum += n }
    return sum
}
println("Sum = ${getSum(1,2,3,4,5)}")