We don’t explicitly need to state the arguments when calling a function in Kotlin. Instead, we can use default arguments. In other words, passing a parameter while calling a function is optional in Kotlin. There are three cases of how arguments may be stated while calling a function. Let’s look at each case in detail.
If we pass all the arguments while calling a function, the default arguments are overwritten and not used. Let’s look at this in the code example below:
// Function Definitionfun person (name: String = "Mike", age: Int = 22) {print("My name is ${name} and I am ${age} years old")}fun main(args: Array<String>) {var name = "Anna"var age = 10// Function Callperson(name,age)}
Line 2: We declare a function named person
that takes two parameters, name
and age
. These two parameters have been assigned default values.
Line 10: We call the function with new values of both the parameters.
When the code is executed, we see that the default arguments get overwritten.
If we pass only some arguments while calling a function, the passed arguments will overwrite the default arguments. For arguments we don’t pass, the default arguments will be used.
Let’s take a look at this case in the code example below:
// Function Definitionfun person (name: String = "Mike", age: Int = 22) {print("My name is ${name} and I am ${age} years old")}fun main(args: Array<String>) {var name = "Anna"// Function Callperson(name)}
Line 2: We declare a function named person
that takes in two parameters, name
and age
. These two parameters have been assigned default values.
Line 9: We call the function with a new value of name
, but we don’t pass the age
parameter in the function call.
As seen in the output, the value of name
gets updated while the default value for age
is used.
If we don’t pass any arguments while calling the function, the default arguments in the function definition are used.
Let’s take a look at this case in the code example below:
// Function Definitionfun person (name: String = "Mike", age: Int = 22) {print("My name is ${name} and I am ${age} years old")}fun main(args: Array<String>) {// Function Callperson()}
Line 2: We declare a function named person
that takes in two parameters, name
and age
. These two parameters have been assigned default values.
Line 8: We call the function without giving it any arguments.
As seen in the output, the default values of name
and age
are used.