Chapter 5.2 : Working with Functions in Kotlin (Android)

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.

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.

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.

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

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.

Protected by Copyscape

Share on Facebook2Share on Google+0Tweet about this on TwitterShare on LinkedIn0Share on Reddit0Pin on Pinterest0Share on Tumblr0Email this to someone