Scala Function Arguments
Arguments are the actual values you pass to a function when you call it. Each argument lands in one parameter, in the order the parameters are written.
A String and an Int together
The label function takes a String parameter and an Int parameter. Each call passes one of each, in that order.
def label(item: String, count: Int): String = item + " x " + count
@main def main(): Unit =
println(label("pens", 4))
println(label("books", 2))One parameter used twice
The body of grow uses the parameter n two times in one expression. One argument therefore feeds both parts of the calculation.
def grow(n: Int): Int = n * n + n
@main def main(): Unit =
println(grow(3))
println(grow(5))Argument order changes the result
subtract takes away the second parameter from the first. Swapping the two arguments gives a different answer, so order matters.
def subtract(a: Int, b: Int): Int = a - b
@main def main(): Unit =
println(subtract(10, 3))
println(subtract(3, 10))Example
def orderLine(item: String, count: Int, price: Int): String =
val total = count * price
item + " total " + total
@main def main(): Unit =
println(orderLine("mug", 2, 150))
println(orderLine("plate", 4, 80))Key points
- Argument: An argument is a value you pass at the call, while a parameter is the named slot that receives it.
- Several parameters: A function can take many parameters, separated by commas in the definition.
- Order: The first argument goes to the first parameter, the second to the second, and so on.
- Repeated use: A parameter can be used many times inside the function body.
- Mixed types: One call can pass different kinds of values, such as a String and an Int together.
In this example, orderLine takes three arguments, a String and two Ints. The body first multiplies count by price to get the total. It then joins the item name and the total into one String, and each call prints its own line.
Note
The argument values must match the parameter types in the definition.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
With def subtract(a: Int, b: Int): Int = a - b, what does subtract(3, 10) give back?