The functions in the previous exercises produced output via println()
statements contained within its code body; however, we also have the ability to return a value from a function.
A return statement returns a value from a function and passes it back to where the function was invoked. This value can then be used throughout our program.
If we want a function to return a value, we must add the return type to the function header as well as a return statement in the body. Take a look at the following example where we create a function that takes in a list of Ints and returns an Int value:
fun listSum(myList: List<Int>): Int { var sum = 0 // iterate through each value and add it to sum for (i in myList) { sum += i } // return statement return sum }
- The return type describes the data type of the value being returned and is stated after the parentheses and a colon
:
in the function header. - The keyword
return
is used to declare a return statement. In this case,sum
is the value being returned. - Any lines of code that exist after the return statement will not be executed.
Previously, we invoked functions by calling them on their own line of code; however, we can also invoke a function and assign it to a variable for later use.
For example, we can set total
to the return value of listSum()
after sending it a list of Int values (billsToPay
):
var billsToPay = mutableListOf(44, 29, 104, 79) // Set total to the return value of listSum(). var total = listSum(billsToPay) println("Your bill total is $total dollars.")
This will output the following:
Your bill total is 256 dollars.
Instructions
Following a recipe for vanilla cake, you are asked to add .75
ounces of vanilla extract; however, you only have a teaspoon to measure the ingredients.
Create a function called ozToTsp()
that takes a Double type argument named oz
and returns a Double type value.
Inside the function, create a variable tsp
whose value is oz
multiplied by 6
. Use a return statement to return the value of tsp
.
Inside main()
, create a variable called tspNeeded
and set its value to ozToTsp()
with an argument of .75
.
Use println()
and a String template to output the following statement:
You will need [tspNeeded] tsp of vanilla extract for this recipe.