Learn
Functions
Named and Default Arguments

We can go further with arguments by naming them or setting default parameter values.

To improve the readability of our code, we can name our arguments when invoking the function. For example, with our calculateForce() function, we can add the names of arguments to our function call:

fun calculateForce(mass: Int, acceleration: Int) { var force = mass * acceleration println("The force is $force Newtons.") } fun main() { // Invoke the function with named arguments. calculateForce(acceleration = 12, mass = 5) // Prints: The force is 60 Newtons. }

Note that by naming our arguments when we invoke a function, we do not need to place the arguments in the same order as they appear in the function header.

Default arguments provide values to function arguments if none are given when the function is called. To implement this, we add an assignment operator and a value after the argument in the function header, like so:

fun greetCustomer(name: String = "Customer") { println("Hello, $name.") }

In the greetCustomer() function, we set the default value of the argument name to "Customer".

If we invoke this function with a String value, that value will become the value of name; however, if no argument is given, name will have a value of "Customer":

greetCustomer("Cynara") // Prints: Hello, Cynara. greetCustomer() // Prints: Hello, Customer.

Instructions

1.

An online shop has a special coupon code to get 15% off a customer’s final purchase.

Create a function called getPrice() that accepts a Double type argument named price as well as a String argument called couponCode that has a default value of "None".

Leave the body empty for now.

2.

Inside the function, declare a Double type variable called finalPrice.

Then, create an if/else expression.

  • If the value of couponCode is "save15", set finalPrice to price * .85.
  • In the else expression, set finalPrice to price.

Outside the conditional, use println() and a String template to output the following statement:

The total price is [finalPrice].
3.

Inside the main() function, invoke getPrice().

When invoking getPrice(), use named arguments to give price a value of 48.0 and couponCode a value of "save15".

4.

Optional:

Invoke getPrice() for a second time. This time, only give the program a single argument: 48.0.

Observe what happens when no argument for couponCode is given.

Folder Icon

Take this course for free

Already have an account?