Basics of Functions and Methods in Scala.

Lavlesh Singh
Analytics Vidhya
Published in
7 min readNov 5, 2020

--

When programs get larger, you need some way to divide them into smaller,
more manageable pieces. For dividing up control flow, Scala offers an approach familiar to all experienced programmers: divide the code into functions. In fact, Scala offers several ways to define functions that are not
present in Java. Besides methods, which are functions that are members
of some object, there are also functions nested within functions, function literals, and function values.

Scala is a functional programming language where it contains both functions as first-class values and methods and has both similarities and dissimilarities. Both the functions and methods are a block of the reusable code also used to store the repeated code in one place, which makes a function call to performs a particular specific task. They also make code easier to debug and modify.

Photo by Cookie the Pom on Unsplash

A function is a set of statements combined together to perform a specific task. The code can be divided logically into separate functions where each function is assigned a specific task.

The function in Scala is a complete object which can be assigned to a variable whereas a method in Scala is a part of class having name, signature, bytecode and annotations. Function name can have characters like ++,+,-,– etc.

However, functions are an object which is initialized in a variable, but methods start with the ‘def’ keyword followed by the method name, parameter list, method body with the return value.

You’ll be learning the following topics:

1-Method declaration and definition
2-Method Call
3-A method with named arguments
4-Default Parameter Values
5-Variable-length Arguments
6-Recursion Function
7-Anonymous Function

Method declaration and definition:- The method in Scala starts with the following parts:

def 'method_name' ('parameters':'return_type_parameters') : ('return_type_of_method') = {
'method_body'
return 'value'
}

The method in Scala starts with the following parts:

1- ‘def’: keyword which is used to declare methods.
2- ‘method_name’: is the name of your method, which is in lower camel case.
3- ‘parameters’: is method parameters that may have no parameter or one parameter only but are separated by a comma when there is more than one parameter.
4- ‘return_type_of_parameters’: need to match according to the data type of ‘parameters_list’ and is compulsory
5- ‘return_type_of_method’: is optional, but in default, ‘Unit’ is returned, but the value can be returned with ‘return’ keyword.
6- Assignment Symbol(‘=’): is optional, and if used will assign the return value and not using it will make the method not to return anything.
7- ‘method_body’: is the block of code enclosed inside curly braces ‘{}’ and consists of the required logic or certain task or operations.
8- return: is the keyword used to return the required values and also terminate the program but is rarely used in Scala.

Method call:- The syntax for Method call in Scala is below:

method_name(arguments)

The Method call can be quickly done by ‘method_name’, which is the name of the corresponding method that you want to call with the arguments is passed.

A method with named arguments:-

The method with named arguments will allow passing the argument to the methods’ parameter during the method call where each of the arguments is matched one by one to the method parameters. You will see the example below of passing the arguments with Function declaration and definition along with the method call in action.

object calculateResult {
def funSub(x:Int, y:Int) : Int =
{

var diff:Int = 0
diff = x — y

// return value
return diff
}
def main(args: Array[String]) {

// Function call
println(“Difference of the value is: “ + funSub(8,6));
println(“Difference of the value is “ + funSub(y=6,x=8));
}
}

The above program gives the output as:
Difference of the value is: 2
Difference of the value is: 2

The above program contains an object ‘calculateResult’, and inside it contains a method named as ‘funSub’ with both the parameters x and y having return type as ‘Int,’ the overall return type of the method is ‘Int’. It is followed by an assignment statement to assign the return value. The curly braces indicate the start of the method body, where the variable ‘diff’ is initialized with the initial value of 0. The Method call ‘funSub(8,6)’ done in the main method matches 8 to ‘x’ and 6 to ‘y,’ and the subtraction operation is carried out, and the value of ‘diff’ is returned and finally gets printed. Similarly, the ‘funSub(x=8,y=6)’ matches 6 to ‘y’ and 8 to ‘x’ to parameters in the method during method call where the order doesn’t matter where a similar operation is done and is return and result gets printed out.

Default Parameter Values:-

You can specify the default values for the method parameters through the initialization of corresponding values and can leave the method call empty by not passing the argument

object calculateResult {
def funSub(x:Int=9, y:Int=6) : Int =
{

var diff:Int = 0
diff = x — y

// return value
return diff
}
def main(args: Array[String]) {

// Function call
print( “The final value is: “ + funSub() );

}
}

The above program gives the output as:
The final value is: 3

You can see the above program contains object defined as ‘calculateResult’ and inside that there is a method named as ‘funSub’ with the parameters x and y with both having return type as ‘Int’ and the overall return type of the method is ‘Int’ and is followed by assignment statement which will assign the return value. The curly braces indicate the start of the method body, where the variable ‘diff’ is initialized with the initial value of 0. The Method call is done inside from the main method where ‘funSub()’ calls and initialize the x to 9 and y to 6, and the operation is carried out, which makes the value ‘diff’ to be returned and printed.

Variable-length Arguments:-

Variable-length Arguments are the arguments that take any variable number of arguments and can be passed by the user or client. The last parameter in the method is declared using ‘*’ which needs to be repeated.

object variableArgument {
def main(args: Array[String]) {
printAll(“Scala”, “is”, “great”)
}

def printAll(strings: String*) {
var i : Int = 0;

for( value <- strings ){
println(value);
i = i + 1;
}
}
}

The above program gives the output as:
Scala
is
great

You can see the above program contains an object ‘variableArgument’ with ‘printAll’ methods where variable-length argument ‘String*’ is defined at the end and during the call of a method a list of strings can be passed. The passed list of strings is looped over and shown as output inside the primary function.

Recursion Function:-
Recursion plays a big role in pure functional programming and Scala supports recursion functions very well. Recursion means a function can call itself repeatedly. Try the following program, it is a good example of recursion where factorials of the passed number are calculated.

object NewObj {
def main(args: Array[String]) {
for (i <- 1 to 5)
println( “Factorial of “ + i + “: = “ + factorial(i) )
}

def factorial(n: BigInt): BigInt = {
if (n <= 1)
1
else
n * factorial(n — 1)
}
}

Out put of the program

Factorial of 1: = 1
Factorial of 2: = 2
Factorial of 3: = 6
Factorial of 4: = 24
Factorial of 5: = 120

Anonymous Function:-

Anonymous Function is those lightweight function definition which doesn’t have a name and is known to be function literal in Scala.

Syntax with example for Anonymous Function are as follows:

  • The first syntax and an example for Anonymous function is:

Syntax:

('first_variable':'data_type', 'second_variable':'data_type') => "certain_expression"

Example:

(var1:String:var2:String) => var1 + var2

The second syntax and an example for Anonymous function is:

(_:'data_type')operator(_'data_type')

Example:

(_:String)+(_:String)

The first syntax shows that expression after “=>” evaluates to a particular value whereas a list of the variable before “=>” used for evaluating the expression. The second syntax above works like a placeholder where it accepts the value as a ‘wild card’ character only once, and then the operator is operated among them.

You’ll see an example of anonymous function below:

object anonymousDemo
{
def main(args: Array[String])
{

var function1 = (var1:Int, var2:Int) => var1 + var2
var function2 = (_:Int) + (_:Int)

// function call
println(function1(5, 5))
println(function2(7, 3))
}
}

The above program gives the output as:
10
10

You can see above the object named to be ‘anonymousDemo’ with the ‘main’ function containing two anonymous functions. They are syntactically different but can produce the same result, where ‘function’1 evaluates by taking parameters from a function call as it is being called — passing the values 5 and 5, which results in output to be printed as 10 whereas ‘function2’ is also called passing 7 and 3 where it receives the value once, which accepts any valid ‘Integer’. In your case, do the addition operation and output the result.

Congratulation, you’ve finished reading this tutorial.

if you enjoyed my this post, So please appreciate after clicking clap button !!

for reading more on Scala, you can refer below links as well.

--

--