In this guide, we will learn default and named argument that are used in Kotlin functions.
Kotlin Default Argument
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.
Default argument example
Not passing any value during function call
fun main(args: Array<String>) { demo() } fun demo(number:Int= 100, ch: Char ='A'){ print("Number is: $number and Character is: $ch") }
Output:
Number is: 100 and Character is: A
In the above example we have not passed any values while calling the function demo()
, lets see what happens when we pass values to the function that already has default values set for their parameters.
Passing value of some of the parameters during function call
fun main(args: Array<String>) { demo(99) } fun demo(number:Int= 100, ch: Char ='A'){ print("Number is: $number and Character is: $ch") }
Output:
As you can see in the output that when we pass values while calling function then it overrides the default values. In the above example I have passed a single value while calling function thats why it overrides only first default value, however we can also pass values for all the parameters and this will override all the default values.
Passing values of all the parameters during function call
fun main(args: Array<String>) { demo(99, 'Z') } fun demo(number:Int= 100, ch: Char ='A'){ print("Number is: $number and Character is: $ch") }
Output:
Number is: 99 and Character is: Z
Kotlin Named Arguments
In the above examples we have learned how we can set default values for the parameters. In the second example we learned that we can call the function while passing few of the values, we have made the function call like this in the second example demo(99)
, it overrides the first default value. However if we want to only override the second default value then we can do this with the help of named arguments.
fun main(args: Array<String>) { demo(ch='Z') } fun demo(number:Int= 100, ch: Char ='A'){ print("Number is: $number and Character is: $ch") }
Output:
As you can see we have overriden the default value of second parameter by using the parameter name during function call demo(ch='Z')
. If we would have done this without named parameter like this demo('Z')
then this would have thrown error because then it would have tried to override the first integer parameter with this value.
Leave a Reply