Using Default & Named Parameters in Kotlin Functions

0
790
Using Default Named Parameters in Kotlin Functions
Using Default Named Parameters in Kotlin Functions
Say Hi! and Follow

Kotlin Default Argument
In Kotlin, you can provide default values to parameters in function definition.We have already learned how a function can have parameters and we can pass the value of those parameters while calling the function, by using default arguments we can set the default value of those parameters while defining a function. Lets take an example to understand default arguments.

If the function is called with arguments passed, those arguments are used as parameters. However, if the function is called without passing argument(s), default argument are used.

The function foo() takes two arguments. The arguments are provided with default values. However, foo() is called by passing both arguments in the above program. Hence, the default arguments are not used.

The value of letter and number will be ‘x’ and 2 respectively inside the foo() function. In most of the programming languages, we need to specify all the arguments that a function accepts while calling that function but in Kotlin, we need not specify all the arguments that a function accepts while calling that function so it is one of the most important features. We can get rid of this constraint and make parameter optional i.e pass an argument or not while calling a function.

Functions are the basic building block of any program. In this article, you’ll learn how to declare and call functions in Kotlin. You’ll also learn about Function scopes, Default arguments, Named Arguments, and Varargs.

Every function declaration has a function name, a list of comma-separated parameters, an optional return type, and a method body. The function parameters must be explicitly typed.

Single Expression Functions

You can omit the return type and the curly braces if the function returns a single expression. The return type is inferred by the compiler from the expression.

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 25,221 other subscribers

Leave a Reply