Functions with named parameters

Kotlin makes it possible to specify the argument's name in a function call. This approach makes the function call more readable and reduces the chance to pass the wrong value to the variable, especially when all variables have the same data type. To understand the importance of this feature, let's take the previous example of currency conversion:

fun currencyExchange(dollar: Double, currencyRate: Double, charges: Double = 5.0): Double {
var total = dollar * currencyRate
var fees = total * charges / 100
total = total - fees
return total
}

The currencyExchange function takes three parameters of the Double type—dollar, target currency, and conversion charges:

fun main (args: Array<String>) {
var total = currencyExchange(100.0, 6.0, 10.0)
println(total)
}

The currencyExchange function will perform the currency conversion and return the result. If the function contains a long list of variables as a parameter, then there is a high chance that values can be passed in the wrong order. In this example, the currency rate is swapped with conversion charges:

var total = currencyExchange(100.0, 6.0, 10.0)
println(total)
Output is 540 instead of 940 Swedish crown.

The program will execute without any errors because arguments passed to the function are the correct types but are in the wrong order. To solve this problem, Kotlin provides a feature called named parameters. Named parameters make it possible to pass different values to the function by explicitly defining a parameter's name. Using the argument's name helps to pass the correct value to each argument and makes the code clean and readable:

total = currencyExchange(dollar = 100.0, currencyRate = 10.0, charges = 6.0)
println(total)

By mentioning the name of each argument, function arguments can pass in any order:

fun main (args: Array<String>) {
var total = currencyExchange(dollar = 100.0, currencyRate = 10.0, charges = 6.0)
println(total)
total = currencyExchange(currencyRate = 10.0, charges = 6.0, dollar = 100.0)
println(total)
}

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

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