21.8 C
Sunday, September 26, 2021

Using Default & Named Parameters in Kotlin Functions




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.

See Also  QR-Code & Barcode Reader Android App
See Also  Code to Create Navigation Drawer in Android App

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.

About the author

SyncSaS Technologies is specialized in creating and designing customized software. We have our own team that will be in charge of developing your softwares.

Add a comment

Related posts