Functions in Scala

Functions in Scala

A function is a collection of statements that perform a certain task. One can divide up the code into separate functions. Functions make code easy to understand and easily debugged.

Declaration of Functions in Scala:

def function_name([parameters]):[return_type]={ //code goes here }

Expansions:

def: It is a keyword that is used to declare a function in scala

function_name : The name of the function which is used to call the trigger. It may consists of lower camel case alphabets and ascii characters.

parameters : Parameters that are used to run the code in the function with comma separated values followed by parameter type.

return_type : The return type of function is optional. If the function return any value ], the datatype of that value shoul br mentioned at return_type.

=: equal to operator is used in scala when the function will return any value. If equal to is not given then the function will not return any value and it is used as subroutine.

Function Calling:

To implement the code that is written in function, the function should be called. There are two ways to call a function in scala.

1.) function_name(paramters)

2.)(instance).function_name(parameters)

Functions with '=' operator:

  1. object MainObject {  
  2.    def main(args: Array[String]) = {  
  3.         functionExample(10,20)   
  4.     }  
  5.     def functionExample(a:Int, b:Int) = {  
  6.           var c = a+b  
  7.           println(c)  
  8.     }  
  9. }  

Output: 30

Functions without '=' operator:

  1. object MainObject {  
  2.    def main(args: Array[String]) {  
  3.         functionExample()           // Calling function  
  4.     }  
  5.     def functionExample()  {        // Defining a function  
  6.           println("This is a simple function")  
  7.     }  
  8. }  

Uses of Functions:

  • Functions can be used to solve problems based on recursion.
  • Once a function is declared, it can be used over and over again. This makes the work easier.
  • A function can improve the readability of code.
  • Debugging of the code would be easier and errors are easily tracked.
  • Reduces the size of the code and duplicate statements are replaced by function calls.


To view or add a comment, sign in

More articles by Hemanth Chintada

  • Decision Tree Classifier

    INTRODUCTION Decision Trees are the foundation for many classical machine learning algorithms like Random Forests…

  • Health, Life Insurance Systems Field Study:

    Team: SDP-375(Health And Life Insurance System) 190030089 Anumula Karthik Reddy (Team Lead) 190030259 Challagulla…

Explore content categories