In a previous lesson, you were introduced to built-in functions; also known as methods. In this chapter, we will cover user-defined functions and learn how to write our very own functions. Let’s get straight to it and look at an example of a user-defined function.
123
def sum(x: Double, y: Double): Double ={
x+y
}
The above function takes two integers and returns their sum. Let’s look at what is exactly happening in the code above.
Syntax
def is the keyword used for defining a function the same way val and var are used for defining variables.
sum is the name of the function which you get to choose yourself. Make sure the name is meaningful to the functionality of the function.
sum is followed by () in which you define the function parameters separated by commas. Parameters specify the type of input to be given to the function.
(x: Double, y: Double) is telling us that our function takes two parameters. The first one is named x and must be of type Double. The second one is named y and must also be of type Double.
After defining the parameters, we define the return type of the function which in our case is Double and is done by inserting : Double after the ().
Inserting the return type is not required as Scala can use type inference to infer the return type of the function.
After defining the function’s return type, we insert a =. Whatever comes after = is the body of the function and defines what the function will do. The body of the function is wrapped in curly brackets {}. You can choose not to use the curly brackets if the function’s body only consists of a single expression.