Kotlin Default and Named Argument

Kotlin Default Argument

Kotlin provides a facility to assign default argument (parameter) in a function definition.

If a function is called without passing any argument than default argument are used as parameter of function definition. And when a function is called using argument, than the passing argument is used as parameter in function definition.

Default argument example 1: passing no argument in function call

Output:

parameter in function definition 5 and x

In the above program, run() function calls with no argument, the default parameter are used in function definition.

Default argument example 2: passing some argument in function call

Output:

parameter in function definition 3 and x

In the above program, run() function calls with one (first) argument, the first parameter of the function definition is uses the value passed to the function. And the second parameter is uses as a default argument.

Default argument example 3: passing all argument in function call

Output:

parameter in function definition 3 and a

As all the arguments are passed in run() function call, the parameters of function definition uses the argument passed in function call.

Kotlin Named Argument

Before we will discuss about the named parameter, let's do some modify in the above program.

For example:

Output:

Error: Kotlin: The character literal does not conform to the expected type Int

Here, we are try to pass parameter 'a' from function call to function definition in the second argument. But compiler assumes that the parameter 'a' (Char type) passed for first argument (Int type) this causes error in program.

Named Argument

To solve the above problem a named argument is used.

A named argument is an argument in which we define the name of argument in the function call. The name defined to argument of function call checks the name in the function definition and assign to it.

Kotlin Named Argument Example

Output:

parameter in function definition 5 and a

Next TopicKotlin Lambdas