Welcome aboard our Scala programming adventure! In this unit, we're delving into functions. In the coding universe, a function serves as a mini-program performing a particular task. It helps to partition more extensive programs into organized, reusable components. Envision functions as home robots, each responsible for a specific task.
To write a Scala function, we define its name and task using this syntax:
Here, the keyword def
declares a function, and Unit
specifies that the function does not return a value. Later in the course, we'll learn how to write functions that return values. Note that we use an indentation to denote the function body, which is the code indicating the function's task. Let's define a function named greet
that extends a friendly message to the world:
This function, named greet
, prints "Hello, World!"
to the console when invoked.
To execute a function, we "call" or "invoke" it using its name followed by parentheses, like so: greet()
. But where do we put this code? In Scala, we can't invoke functions directly from the top level. Instead, we can define a special function called the main function, which serves as the entry point to your entire application.
