In this tutorial you will learn about the Kotlin Default Argument and its application with practical example.
Kotlin Function Argument
In Kotlin, we pass information in function call as its arguments and the function can either returns some value to the point it where it called from or returns nothing.
Kotlin Default Argument
Kotlin supports to assign default argument (parameter) values in a function definition, so when we call that function with no argument passed for a parameter then its default value assigned. When a function is called with argument, then these arguments is used as parameter values in function, but when a function is called or invoked without passing argument for any specific parameters than default parameter values been used as parameters value as per function definition.
Syntax:-
1 2 3 |
fun <function_name>(<param1_name: param1_type,param2_name: param2_type = default_value>){ // function body } |
Example :- Function call with all arguments passed
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main(args: Array<String>) { // function call with all arguments passed addnum(15,25) } /** * n1 : default argument is 5 * n2 : default argument is 10 */ fun addnum(n1:Int = 5, n2:Int = 10){ val result=n1+n2 print("Sum of $n1 and $n2 is : $result") } |
Output:-
1 |
Sum of 15 and 25 is : 40 |
Example :- Function call with some arguments passed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun main(args: Array<String>) { // function call with some arguments passed addnum(15) } /** * n1 : default argument is 5 * n2 : default argument is 10 */ fun addnum(n1:Int = 5, n2:Int = 10){ val result=n1+n2 print("Sum of $n1 and $n2 is : $result") } |
Output:-
1 |
Sum of 15 and 10 is : 25 |
Example:- Function call with no arguments passed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun main(args: Array<String>) { // function call with no arguments passed addnum() } /** * n1 : default argument is 5 * n2 : default argument is 10 */ fun addnum(n1:Int = 5, n2:Int = 10){ val result=n1+n2 print("Sum of $n1 and $n2 is : $result") } |
Output:-
1 |
Sum of 5 and 10 is : 15 |