Functions
Scala has both functions and methods and we use the terms method and function interchangeably with a minor difference. A Scala method is a part of a class that has a name, a signature, optionally some annotations, and some bytecode whereas a function in Scala is a complete object which can be assigned to a variable. In other words, a function, which is defined as a member of some object, is called a method.
Function Declarations
A Scala function declaration has the following form −
def functionName ([list of parameters]) : [return type] |
Methods are implicitly declared abstract if you don’t use the equals sign and the method body.
Function Definitions
A Scala function definition has the following form −
Syntax
def functionName ([list of parameters]) : [return type] = { function body return [expr] } |
Here, the return type could be any valid Scala data type and the list of parameters will be a list of variables separated by a comma and the list of parameters and return type are optional.
Calling Functions
Scala provides several syntactic variations for invoking methods. Following is the standard way to call a method −
functionName( list of parameters ) |
If a function is being called using an instance of the object, then we would use dot notation similar to Java as follows −
[instance.]functionName( list of parameters ) |
Closures
Scala Closures are functions which uses one or more free variables and the return value of this function is dependent of these variable. The free variables are defined outside of the Closure Function and are not included as a parameter of this function. So the difference between a closure function and a normal function is the free variable. A free variable is any kind of variable which is not defined within the function and not passed as the parameter of the function. A free variable is not bound to a function with a valid value. The function does not contain any values for the free variable.
0 Comments