Saturday 27 January 2018

Kotlin: Call functions using parameter names

In Kotlin, you can call the functions using parameter names, this is similar to 'Keyword arguments' feature in python.

fun printEmployee(id: String, firstName: String, lastName: String, designation: String) {
         println("\nid : $id\nfirstName : $firstName\nlastName : $lastName\ndesignation : $designation")
}

In kotlin, you can call the function by using the parameter names.
printEmployee(id = "1", firstName = "krishna", lastName = "Gurram", designation = "engineer")

One advantage of specifying parameter names is, you can change the arguments order while calling the function.
printEmployee(designation = "engineer", firstName = "krishna", lastName = "Gurram", id = "1")

KeyWordArgsDemo.kt

fun printEmployee(id: String, firstName: String, lastName: String, designation: String) {
 println("\nid : $id\nfirstName : $firstName\nlastName : $lastName\ndesignation : $designation")
}


fun main(args: Array<String>) {
 printEmployee("1", "krishna", "Gurram", "Engineer")

 printEmployee(id = "1", firstName = "krishna", lastName = "Gurram", designation = "engineer")
 printEmployee(designation = "engineer", firstName = "krishna", lastName = "Gurram", id = "1")
}

Output

id : 1
firstName : krishna
lastName : Gurram
designation : Engineer

id : 1
firstName : krishna
lastName : Gurram
designation : engineer

id : 1
firstName : krishna
lastName : Gurram
designation : engineer


Previous                                                 Next                                                 Home

No comments:

Post a Comment