Named arguments

We can use a named argument to invoke a function and pass the arguments by naming them. Since the arguments are named, the order doesn't need to be maintained.

Let's take a look at the following example. Consider the code for 6f_NamedArguments.kts:

fun welcome(name: String, msg:String = "Hey") {
println("$msg $name")
}
welcome(msg = "How are you", name = "Mark")

The output is as follows:

We can also mix named arguments with arguments without a name. Consider the code for 6g_NamedArguments.kts:

fun welcome(name: String, msg:String = "Hey") {
println("$msg $name")
}
welcome("Joseph", msg = "Hi")

The output is as follows:

In this case, we invoked the function with one positional argument with the value Joseph and one argument named msg. When we are dealing with multiple arguments in a method, we can choose to send some arguments positionally by maintaining the order and to send others as named arguments. The language gives us the flexibility to invoke functions with type safety.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset