scala named function
In Scala, a named function is a function that is given a specific name and can be called by that name. Here's an example of how to define a named function in Scala:
def addNumbers(a: Int, b: Int): Int = {
a + b
}
In this example, we define a function named addNumbers
that takes two integer parameters a
and b
, and returns their sum as an integer. The def
keyword is used to declare the function, followed by the function name and the parameter list in parentheses. After the parameter list, we specify the return type using a colon (:
) followed by the desired type. In this case, the return type is Int
.
Inside the function body, we simply add the values of a
and b
using the +
operator, and the result is automatically returned as the result of the function.
To call the addNumbers
function, you can simply write its name followed by the arguments in parentheses:
val result = addNumbers(5, 7)
println(result)
In this example, we call the addNumbers
function with arguments 5
and 7
, and store the result in a variable named result
. We then print the value of result
using the println
function.
This is how you define and call a named function in Scala.