Functions with default arguments

Kotlin makes it possible to assign a value to a parameter in the function declaration. If the function is invoked without passing a value, then the compiler automatically assigns a default value to it. The hello function prints Hello Kotlin if no value is passed to the function:

fun hello(message : String = "Kotlin") : Unit{
println("Hello $message")
}

fun main (args: Array<String>) { hello()
hello("World")
}

The default argument is a very helpful feature in many situations. For example, consider a situation in which we are writing a currency exchange function that converts dollars into another currency and applies service charges on the conversion:

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

Let's assume that we want to convert 100 US dollars to Swedish krona. 1 dollar is equal to 10 Swedish krona, and our company charges 5% on the total amount:

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

This function works fine; it multiplies the dollar by the target currency, calculates the charges, and returns the total amount after deductions. In the currency market, currency prices move quite rapidly, so it is a good idea to check the currency rate before conversion. However, its highly likely that conversion charges (5% in this example) will remain the same for a long period of time. If this is true, then the default value can be assigned to the charges variable, as follows:

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
}

By setting the default value, the function can be invoked without a third parameter:

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

var
total = currencyExchange(100.0,10.0, 3.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
13.58.51.228