Learn
Functions
Creating and Calling a Function

In order to declare a function, we’ll need to understand the anatomy of a basic function.

A function header contains valuable information about a function including its name, arguments, and its return type.

fun funcName(argName: Type): returnType {
  Function Body
}
  • The fun keyword is used to declare a function.
  • The function name is used to call the function throughout the program.
  • Inside the parentheses are arguments- pieces of data fed to the function.
  • The return type declares the type of data the function will return; it is also optional to include.
  • Following the function header is the function’s body where instructions are contained.

We’ll cover arguments and return types later in this lesson. For now, we’ll focus our attention on creating a basic function that outputs a value whenever we call it.

Let’s create a function called greeting() that prints "Hello friend!":

fun greeting() { println("Hello friend!") }

A function will only execute when it is called or invoked. While the function greeting() will exist outside the main() function, we will call greeting() within main() by writing the function’s name followed by parentheses:

fun greeting() { println("Hello friend!") } fun main() { // Invoke the function greeting() } // Prints: Hello friend!

Anytime we call greeting(), "Hello, friend!" will be outputted to the terminal.

Instructions

1.

Create a function named smores() that outputs the following statements using println():

  • "Roast a marshmallow."
  • "Place marshmallow on a graham cracker."
  • "Place chocolate on marshmallow."
  • "Put a new graham cracker on chocolate."
  • "Enjoy!"
2.

Invoke smores() in the main() function.

3.

Optional:

Call smores() again. Note how time is saved by calling a function instead of writing the instructions again.

Folder Icon

Take this course for free

Already have an account?