In this article, you will learn about functions with a variable number of arguments and infix notation.

Before moving to current topic, I explained Kotlin from beginning and you can find full list of previous tutorial at **Kotlin** page.

### Variable arguments

You can pass variable number of argument of same type by declaring function with a `vararg`

parameter. In Kotlin, a `vararg`

parameter of type `T`

is internally represented as an array of type `T (Array`

inside the function body.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun sumOfNumbers(vararg numbers: Int): Int { var sum: Int = 0 for(number in numbers) { sum += number } return sum } >>> println("Sum : " + sumOfNumbers(1, 2)); >>> println("Sum : " + sumOfNumbers(1, 2, 3)); >>> println("Sum : " + sumOfNumbers(1, 2, 3, 4)); //Sum : 3 //Sum : 6 //Sum : 10 |

In above examples, we have passed variable numbers of arguments in the function. This kind of functionality is very much useful when the same type of argument is required.

We can also pass multiple arguments with `vararg`

parameter. We need to take care while calling that function by named argument.

1 2 3 4 5 6 7 8 9 10 11 |
fun sumOfNumbers(vararg numbers: Int, initialValue : Int): Int { var sum: Int = initialValue for(number in numbers) { sum += number } return sum } >>> println("Sum : " + sumOfNumbers(1, 2, initialValue = 10)); //Sum : 13 |

### Infix notation

Kotlin is providing variety of facility to users and `infix notation`

is one of it. By using this in function, we can call that function using the infix notation (omitting the dot and the parentheses for the call). There are 3 conditions which have to be satisfied.

- must be member functions
- must have a single parameter
- parameter must not accept variable number of arguments and must have no default value

We need to fulfil above 3 condition then only we can use `infix notation`

in function.

1 2 3 4 5 6 7 |
infix fun Int.add(x : Int) : Int { return this + x; } >>> println("Sum : " + 2.add(5)) //Sum : 7 |

We can also use this infix notation in class level function.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
data class Calculator(val value: Double) { // Infix function for adding two complex numbers infix fun add(c: Calculator): Calculator { return Calculator(value + c.value) } } val c1 = Calculator(3.0) val c2 = Calculator(4.0) // Infix call // produces - Calculator(value = 7.0) val c3 = c1 add c2 >>> println("Result : " + c3.value) //Result : 7.0 |

Don’t be surprised. This is the power of functional programming. Functional programming provides more readability with powers to handle code. Enjoy coding!

### Summary

In this article, you learned how to deal with function with variable arguments and infix notation. In next article, we will be going to learn about function scope.

Thanks for reading. Please ask any doubts in the comment. Don’t forget to share this article.