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.



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!"

Invoke smores() in the main() function.



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

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?