Learn
Functions
Arguments

Arguments are pieces of data we can feed to our functions in order to produce dynamic results. We can include as many arguments as the function needs.

Think of the println() function. When we use it, we give it a single argument: a String value. This value is then passed and outputted to the terminal.

To pass arguments into a function, we need to add parameters to our function header. Parameters are the names given to data being passed into a function. For example:

fun calculateForce(mass: Int, acceleration: Int) { var force = mass * acceleration println("The force is $force Newtons.") }

In the parentheses of the function header, we added two parameters: mass and acceleration.

  • Each parameter is separated by a comma (,).
  • The parameter starts with its name, followed by a colon (:), and then the parameter type.

The parameters can then be referenced within the function body like a variable. The value of each parameter is determined by the arguments used when invoking the function:

calculateForce(5, 12)

When calculateForce() is called, the values 5 and 12 are passed as arguments into the function. The value of the parameter mass will be 5 and the value of acceleration will be 12. Invoking the function with these argument values will give us the following output:

The force of this object is 60 Newtons.

An important concept to understand with functions is scope. Scope dictates the environment in which a variable can be accessed within a program. If we were to try and reference the variable force anywhere in our program outside of the calculateForce() function, we would receive an error because the variable only exists within that function.

Instructions

1.

Create a function called getSpeed() that accepts two Int arguments: distance and time.

Inside the function, create a variable called speed that is equal to the value of distance / time.

Use println() and a String template to output the following statement:

[speed] meters per second
2.

Invoke the getSpeed() function inside main().

Set the argument value of distance to 10 and the value of time to 3.

Folder Icon

Take this course for free

Already have an account?