In this tutorial you will learn about the Kotlin Named Argument and its application with practical example.
Kotlin Named Argument
Kotlin named arguments allow us to pass an argument/value for specific function parameter by specifying parameter name in function call. This way it resolve the issue of conflict in argument list when we want to pass selected parameter arguments.
Example:- function call with named argument
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun main(args: Array<String>) { // function call with named argument addnum(n2=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 5 and 15 is : 20 |
Here, we are using named argument (n2=15) specifying that the n2 parameter in the function definition will take this value (doesn’t matter the position of the argument).